简体   繁体   中英

Check if a CIDR contains public IP addresses - In Java

Given a CIDR string, i would like to test whether or not this CIDR contains IP addresses that are not reserved as private addresses (ie is whitin one of the following ranges :)

192.168.0.0 - 192.168.255.255
172.16.0.0 - 172.31.255.255
10.0.0.0 - 10.255.255.255

Parse it into an InetAddress , then check its bytes .

int slash = cidr.indexOf('/');
String ip = cidr.substring(0, slash);
InetAddress address = InetAddress.getByName(ip);
byte[] bytes = address.getAddress();
boolean privateAddress =
    (bytes[0] == 10) ||
    (bytes[0] == (byte) 172 && (bytes[1] >= 16 && bytes[1] < 32)) ||
    (bytes[0] == (byte) 192 && bytes[1] == (byte) 168);

Or, you could just check the string directly:

boolean privateAddress =
    cidr.startsWith("10.") || cidr.startsWith("192.168.") ||
    cidr.matches("172\\.(1[6-9]|2[0-9]|3[01])\\..*");

Personally, I would opt for the first approach; shorter isn't aways better. I'd rather rely on a parser that handles every corner case of IPv4 address notation.

最终为私有范围定义了静态CIDR块,并使用以下代码查看它是否与给定的CIDR重叠-https: //gist.github.com/nacx/8837081716c5b333d7edc8bec4684482

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM