我有 IP 地址和掩码,例如 10.1.1.1/32
。我想检查 10.1.1.1
是否在该范围内。是否有库或实用程序可以执行此操作,还是我需要自己编写一些东西?
最佳答案
首先,您需要将您的 IP 地址转换为平面 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 地址为纯 int
,您就可以执行一些位算术来执行检查:
int subnet = 0x0A010100; // 10.1.1.0/24
int bits = 24;
int ip = 0x0A010163; // 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.
}
关于java - 验证 IP 地址(带掩码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4209760/