从网上借鉴了方法,实现获得本机的众多IP中,指定某个网段的IP地址,这里是指局域网环境下,偷懒的方式,只比较了IP地址的第三个数字,严谨的来说,需要根据子网掩码来获得网段地址,进而逐个比较的。
byte charToInt(char * str, int start_idx, int end_idx)
{
int a = 0, i;
for (i = start_idx; i <= end_idx; ++i)
{
a = a * 10 + (str[i] - '0');
}
return (byte)a;
}
int CutIPtoInt(char * ip, int iCutSet)
{
int start = 0, i = 0, ret = 0, ia = 0;
int shift_factor = 1; //
char c;
while (c = ip[i])
{
if (c == '.')
{
ia = charToInt(ip, start, i - 1);
if (shift_factor == iCutSet)
return ia;
++shift_factor;
start = i + 1;
}
i++;
}
return ret;
}
bool IsSameNetSegment(char* pIpA, char* pIpB)
{
bool bRtn = false;
int iIpA = CutIPtoInt(pIpA, 3);
if (iIpA == CutIPtoInt(pIpB, 3))
bRtn = true;
return bRtn;
}
char* GetTheSameNetSegmentIPaddr(char * pTargetIP)
{
char szHost[256] = "";
char szIp[256] = "";
//取得本地主机名
::gethostname(szHost, 256);
//通过主机名得到地址信息
hostent *pHost = ::gethostbyname(szHost);
//char* pTargetIP = "192.168.5.30";
in_addr addr;
for (int i = 0;; i++)
{
//p指向一个32位的IP地址
char *p = pHost->h_addr_list[i];
if (p == NULL)
{
break;
}
memcpy(&addr.S_un.S_addr, p, pHost->h_length);
char *szIpTemp = ::inet_ntoa(addr);
if (IsSameNetSegment(pTargetIP, szIpTemp))
{
strcpy_s(szIp, szIpTemp);
return szIp;
}
}
return "127.0.0.1";
}