下面的代码使用 IPAddress Java 库(免责声明:我是项目经理)使用 IPv4 和 IPv6 地址处理此问题,并且还避免了对无效字符串的 DNS 查找。
以下是一些示例代码,其中包含您给定的地址以及一些 IPv6 地址:
static void range(String lowerStr, String upperStr, String str)
throws AddressStringException {
IPAddress lower = new IPAddressString(lowerStr).toAddress();
IPAddress upper = new IPAddressString(upperStr).toAddress();
IPAddress addr = new IPAddressString(str).toAddress();
IPAddressSeqRange range = lower.toSequentialRange(upper);
System.out.println(range + " contains " + addr + " " + range.contains(addr));
}
range("192.200.0.0", "192.255.0.0", "192.200.3.0");
range("2001:0db8:85a3::8a2e:0370:7334", "2001:0db8:85a3::8a00:ff:ffff",
"2001:0db8:85a3::8a03:a:b");
range("192.200.0.0", "192.255.0.0", "191.200.3.0");
range("2001:0db8:85a3::8a2e:0370:7334", "2001:0db8:85a3::8a00:ff:ffff",
"2002:0db8:85a3::8a03:a:b");
输出:
192.200.0.0 -> 192.255.0.0 contains 192.200.3.0 true
2001:db8:85a3::8a00:ff:ffff -> 2001:db8:85a3::8a2e:370:7334 contains 2001:db8:85a3::8a03:a:b true
192.200.0.0 -> 192.255.0.0 contains 191.200.3.0 false
2001:db8:85a3::8a00:ff:ffff -> 2001:db8:85a3::8a2e:370:7334 contains 2002:db8:85a3::8a03:a:b false