计算IP地址是否在Java中的指定范围内

She*_*ari 30 java ip-address

我希望能够返回true/false,具体取决于IP在两个其他IP的范围内.

例如:

ip 192.200.3.0

range from 192.200.0.0

range to 192.255.0.0

应该是真的.

其他例子:

assert 192.200.1.0 == true
assert 192.199.1.1 == false
assert 197.200.1.0 == false
Run Code Online (Sandbox Code Playgroud)

hal*_*ave 65

检查范围的最简单方法可能是将IP地址转换为32位整数,然后只比较整数.

public class Example {
    public static long ipToLong(InetAddress ip) {
        byte[] octets = ip.getAddress();
        long result = 0;
        for (byte octet : octets) {
            result <<= 8;
            result |= octet & 0xff;
        }
        return result;
    }

    public static void main(String[] args) throws UnknownHostException {
        long ipLo = ipToLong(InetAddress.getByName("192.200.0.0"));
        long ipHi = ipToLong(InetAddress.getByName("192.255.0.0"));
        long ipToTest = ipToLong(InetAddress.getByName("192.200.3.0"));

        System.out.println(ipToTest >= ipLo && ipToTest <= ipHi);
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是InetAddress.getByName(),您可能希望查看具有InetAddresses帮助程序类的Guava库,以避免DNS查找的可能性.