代码语言:javascript复制因为今天做的一个项目有个需求是判断某个地址是否为公网或私网IP,所以简简单单写了下面方法。可能会有问题,大家多多指教咯。
/**
* 10.0.0.0 - 10.255.255.255
* 172.16.0.0 - 172.31.255.255
* 192.168.0.0 - 192.168.255.255
*/
static bool is_private_address(QString ip)
{
uint32_t address = QHostAddress(ip).toIPv4Address();
uint32_t check1 = (10 << 24); // 0x0a000000
uint32_t check2 = (172 << 24) (16 << 16); // 0xac100000
uint32_t check3 = (192 << 24) (168 << 16); // 0xc0a80000
/* 10.0.0.0 - 10.255.255.255 */
if ((address & 0x0f000000) == check1)
return true;
/* 172.16.0.0 - 172.31.255.255 */
if ((address & 0xfff00000) == check2)
return true;
/* 192.168.0.0 - 192.168.255.255 */
if ((address & 0xffff0000) == check3)
return true;
return false;
}