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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4256438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:05:00  来源:igfitidea点击:

Calculate whether an IP address is in a specified range in Java

javaip-address

提问by Shervin Asgari

I want to be able to return true/false depending on an IP being in range of two other IPs.

我希望能够根据 IP 在其他两个 IP 的范围内返回真/假。

For instance:

例如:

ip 192.200.3.0

ip 192.200.3.0

range from 192.200.0.0

range from 192.200.0.0

range to 192.255.0.0

range to 192.255.0.0

should result to true.

应该结果为真。

Other examples:

其他例子:

assert 192.200.1.0 == true
assert 192.199.1.1 == false
assert 197.200.1.0 == false

采纳答案by hallidave

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

检查范围的最简单方法可能是将 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);
    }
}

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

而不是InetAddress.getByName(),您可能想查看 Guava 库,它有一个InetAddresses帮助器类,可以避免 DNS 查找的可能性。

回答by Sean F

The following code, using the IPAddress Java library(Disclaimer: I am the project manager) handles this with both IPv4 and IPv6 addresses, and also avoids DNS lookup on invalid strings.

以下代码使用IPAddress Java 库(免责声明:我是项目经理)使用 IPv4 和 IPv6 地址处理此问题,并避免对无效字符串进行 DNS 查找。

Here is some sample code with your given addresses as well as some IPv6 addresses:

以下是一些包含给定地址和一些 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");

Output:

输出:

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