函数IsLAN可以直接使用,其中硬编码的计算来自下边第二段代码
BOOL IsLAN(const struct sockaddr FAR * lpTo)
{
int ip = ((sockaddr_in*)lpTo)->sin_addr.s_addr;
if (ip >= 0x0a000000 && ip <= 0x0affffff) // A类地址
return TRUE;
else if (ip >= 0xac100000 && ip <= 0xac1fffff) // B类地址
return TRUE;
else if (ip >= 0xc0a80000 && ip <= 0xc0a8ffff) // C类地址
return TRUE;
else if (ip == 0x7f000001) // 127.0.0.1
return TRUE;
else
return FALSE;
}
这个代码是我用来计算各类地址起始的测试
#include "stdafx.h"
#include "Winsock2.h"
#include <string>
#pragma comment(lib, "ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
/*--------------------------------------------------------------------------------------------
局域网IP地址范围 Little Endia network byte order decimal
A: 10.0.0.0-10.255.255.255 0000000a ~ ffffff0a 0x0a000000 ~ 0x0affffff 10 ~ -246
B: 172.16.0.0-172.31.255.255 000010ac ~ ffff1fac 0xac100000 ~ 0xac1fffff 4268 ~ -57428
C: 192.168.0.0-192.168.255.255 0000a8c0 ~ ffffa8c0 0xc0a80000 ~ 0xc0a8ffff 43200 ~ -22336
127.0.0.1 0x0100007f 0x7f000001
--------------------------------------------------------------------------------------------*/
//sockaddr_in addr;
//addr.sin_addr = (IN_ADDR)inet_addr("10.0.0.0");
UINT aBegin = htonl(inet_addr("10.0.0.0"));
UINT aEnd = htonl(inet_addr("10.255.255.255"));
UINT bBegin = htonl(inet_addr("172.16.0.0"));
UINT bEnd = htonl(inet_addr("172.31.255.255"));
UINT cBegin = htonl(inet_addr("192.168.0.0"));
UINT cEnd = htonl(inet_addr("192.168.255.255"));
printf("%08x ~ %08x\n", aBegin, aEnd);
printf("%08x ~ %08x\n", bBegin, bEnd);
printf("%08x ~ %08x\n", cBegin, cEnd);
if (argc == 2) {
int ip = htonl(inet_addr(argv[1]));
std::string type;
if (ip >= aBegin && ip <= aEnd)
type = "a类ip地址";
else if (ip >= bBegin && ip <= bEnd)
type = "b类ip地址";
else if (ip >= cBegin && ip <= cEnd)
type = "c类ip地址";
else
type = "外网ip地址";
printf("%s : %08x\n", type.c_str(), ip);
}
printf("127.0.0.1 host byte order: %08x\n", inet_addr("127.0.0.1"));
printf("127.0.0.1 network byte order: %08x\n", htonl(inet_addr("127.0.0.1")));
system("pause");
return 0;
}