计算IP地址是否在Java中的指定范围内 [英] Calculate whether an IP address is in a specified range in Java

查看:545
本文介绍了计算IP地址是否在Java中的指定范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

ip 192.200.3.0

范围从192.200。 0.0

范围为192.255.0.0

应该为真。

其他例子:

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


推荐答案

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

这篇关于计算IP地址是否在Java中的指定范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆