首先,您需要将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/24int 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 == 0xFFFFFF00mask = -1 << (32 - bits)if ((subnet & mask) == (ip & mask)) { // IP address is in the subnet.}


