现在的位置: 首页 > 综合 > 正文

获取局域网内所有IP

2018年07月17日 ⁄ 综合 ⁄ 共 1125字 ⁄ 字号 评论关闭
void GetAllIPInLan(const string &strGateway, vector<string> &vsIP)
{
	vector<string> vsDest;
	split(strGateway, ".", vsDest);

	int arriIP[4];
	for (int i = 0; i < 4; ++i)
	{
		arriIP[i] = atoi(vsDest[i].c_str());
	}

	// iResult存储的是192.168.1.1按照32bit的形式存储的值
	unsigned iResult = 0;
	for (int i = 0; i < 4; ++i)
	{
		iResult |= arriIP[i] << (3 - i) * 8;
	}

	unsigned iSubNetMask = 22;	// 子网掩码

	// iResult存放的是跟子网掩码按位与以后的结果,然后将其末尾加上可能的子网号
	iResult &= 0xffffffff << (BITS - iSubNetMask);

	string strIP, strTemp;
	for (int i = 0; i < 1 << (BITS - iSubNetMask); i++)
	{
		strIP.clear();

		// tmp是某个局域网IP的32bit表示, 分别抽出8bit就构造出IP地址
		int tmp = iResult | i;
		for (int j = 0; j < 4; j++)
		{
			arriIP[j] = (unsigned)(tmp & 0xff << (3 - j) * 8) >> (3 - j) * 8;

			strTemp.clear();
			itostr(strTemp, arriIP[j]);
			strIP = strTemp + (j == 4 ? "" : ".");
		}

		vsIP.push_back(strIP);
	}
}
void split(const string &src, const string &separator, vector<string> &dest)
{
	string str = src;
	string substring;
	string::size_type start = 0, index;

	do
	{
		index = str.find_first_of(separator,start);
		if (index != string::npos)
		{    
			substring = str.substr(start,index-start);
			dest.push_back(substring);
			start = str.find_first_not_of(separator,index);

			if (start == string::npos) return;
		}
	}while (index != string::npos);

	//the last token
	substring = str.substr(start);
	dest.push_back(substring);
}

抱歉!评论已关闭.