[JAVA] Find the subnet mask from the network prefix length

Main.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;

public class Main {
    public static void main(String[] args) throws Exception {
        String addr = "192.168.1.100/24";

        String[] parts = addr.split("/");
        String ip = parts[0];
        int prefix;
        if (parts.length < 2) {
            prefix = 0;
        } else {
            prefix = Integer.parseInt(parts[1]);
        }
        
        int mask = 0xffffffff << (32 - prefix);
        System.out.println("Prefix=" + prefix);
        System.out.println("Address=" + ip);
        
        int value = mask;
        byte[] bytes = new byte[]{
            (byte) (value >>> 24), (byte) (value >> 16 & 0xff), (byte) (value >> 8 & 0xff), (byte) (value & 0xff)
        };
        
        InetAddress netAddr = InetAddress.getByAddress(bytes);
        System.out.println("Mask=" + netAddr.getHostAddress());
        
    }
}

Recommended Posts

Find the subnet mask from the network prefix length
Find the average age from List <Person>.
Find the difference from a multiple of 10