LoginSignup
0
0

More than 5 years have passed since last update.

ネットワークプリフィックス長からサブネットマスクを求める

Posted at
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());

    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0