且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-10 06:02:13

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

The easiest way to check the range is probably to convert the IP addresses to 32-bit integers and then just compare the integers.

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);
    }
}

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

Rather than InetAddress.getByName(), you may want to look at the Guava library which has an InetAddresses helper class that avoids the possibility of DNS lookups.