参考:https://zhidao.baidu.com/question/191740827.html
私有IP地址范围:
A: 10.0.0.0 10.255.255.255 10.0.0.0/8B: 172.16.0.0 172.31.255.255 172.16.0.0/12C: 192.168.0.0 192.168.255.255 192.168.0.0/16 在C语言中的 socket 结构体如下struct sockaddr_in { short sin_family; USHORT sin_port; IN_ADDR sin_addr; CHAR sin_zero[8];}
其中IP 地址字段为 sin_addr,当选择IPv4类型的IP地址时,sin_addr 是一个网络字节序的4字节的数字。
sample:
192.168.207.1 c0 a8 cf 01Filter:
A: startwith 10.x.x.x B: startwith 172.(16~31).x.x C: startwith 192.168.x.x判断顺序:
A -> C -> B
伪码如下:
char data[4] = NetworkAddr;
if data[0] == 10:
return true elif data[0] == 192 and data[1] == 168: return true elif data[0] == 172: if data[1] >= 16 and data[1] <= 31: return trueelse: return False
#include#include #include #pragma comment(lib,"ws2_32.lib") // inet_addr()BOOL isLocalAddr(DWORD netAddr){ unsigned char data[4]; BOOL bRet = FALSE; memcpy(data, (char *)&netAddr, 4); if (10 == data[0]) { bRet = TRUE; } else if (192 == data[0] && 168 == data[1]) { bRet = TRUE; } else if (172 == data[0]) { if (data[1] >= 16 && data[1] <= 31) { bRet = TRUE; } } else if(!memcmp(data, servAddr, 4)) { bRet = TRUE; } return bRet;}int main(){ char *addrList[] = { "192.168.207.1", "192.12.1.3", "172.16.2.1", "172.33.1.1", "10.12.12.1", "43.1.31.23", }; char *result[] = { "X Local Address", "O Local Address" }; int addrCnt = sizeof(addrList) / sizeof(addrList[0]); DWORD netAddr = 0; BOOL ret = FALSE; for (int i = 0; i < addrCnt; i++) { netAddr = inet_addr(addrList[i]); ret = isLocalAddr(netAddr); printf("%-16s [%s]\n", addrList[i], result[ret]); } return 0;}
运行结果: