從網上借鑑了方法,實現獲得本機的衆多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";
}