How to get Subnet from an IP in Java

1.8k views Asked by At

How do I get the subnet value from an IP Address. For eg, we can do below in Python. (But how about Java?)

interface = ipaddress.IPv4Interface('11.22.104.0/0.0.0.255')
value = interface.with_prefixlen

Output of value = 11.22.104.0/24

Basically, I need a function to convert 0.0.0.255 into /24. Thanks.

Edit

-Java 7 is used.

2

There are 2 answers

4
shmosel On BEST ANSWER

With Guava:

int slash = Integer.bitCount(
        ~Ints.fromByteArray(
                InetAddresses.forString("0.0.0.255").getAddress()));

With Java 8:

int slash = Arrays.stream("0.0.0.255".split("\\."))
        .mapToInt(Integer::parseInt)
        .map(i -> ~i & 0xFF)
        .map(Integer::bitCount)
        .sum();

With Java 7:

int slash = 0;
for (String octet : "0.0.0.255".split("\\.")) {
    slash += Integer.bitCount(~Integer.parseInt(octet) & 0xFF);
}

The value of slash will be 24.

0
Sean F On

The IPAddress Java library supports both IPv4 and IPv6 subnets in a polymorphic manner. Disclaimer: I am the project manager. The following code will convert a host mask to a prefix length:

IPAddressString maskString = new IPAddressString("0.0.0.255");
IPAddress mask = maskString.toAddress();
Integer prefLen = mask.getBlockMaskPrefixLength(false);//24