一尘不染

验证IP地址(带掩码)

java

我有IP地址和掩码,例如10.1.1.1/32。我想检查是否10.1.1.1在该范围内。是否存在可以执行此操作的库或实用程序,或者我需要自己写点东西?


阅读 745

收藏
2020-12-03

共1个答案

一尘不染

首先,您需要将IP地址转换为flat int,这将更易于使用:

String       s = "10.1.1.99";
Inet4Address a = (Inet4Address) InetAddress.getByName(s);
byte[]       b = a.getAddress();
int          i = ((b[0] & 0xFF) << 24) |
                 ((b[1] & 0xFF) << 16) |
                 ((b[2] & 0xFF) << 8)  |
                 ((b[3] & 0xFF) << 0);

一旦您的IP地址为ints,就可以执行一些算法来执行检查:

int subnet = 0x0A010100;   // 10.1.1.0/24
int bits   = 24;
int ip     = 0x0A010199;   // 10.1.1.99

// Create bitmask to clear out irrelevant bits. For 10.1.1.0/24 this is
// 0xFFFFFF00 -- the first 24 bits are 1's, the last 8 are 0's.
//
//     -1        == 0xFFFFFFFF
//     32 - bits == 8
//     -1 << 8   == 0xFFFFFF00
mask = -1 << (32 - bits)

if ((subnet & mask) == (ip & mask)) {
    // IP address is in the subnet.
}
2020-12-03