java ip 范围内打卡,计算IP地址是否在Java中的指定范围内

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

For instance:

ip 192.200.3.0

range from 192.200.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

解决方案

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

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值