Java: IPv4 addresses, masks, and CIDR blocks

An IPv4 address is a 32-bit number, usually written as four decimal bytes. CIDR notation such as /26 says that the first 26 bits identify the network and the remaining 6 bits identify the host. The subnet mask has ones in the network bits and zeros in the host bits.

Java
class Main {
  static int toInt(String ip) {
    int value = 0;
    for (String part : ip.split("\\.")) {
      value = (value << 8) | Integer.parseInt(part);
    }
    return value;
  }

  static String toText(int value) {
    return ((value >>> 24) & 255) + "." + ((value >>> 16) & 255) + "."
        + ((value >>> 8) & 255) + "." + (value & 255);
  }

  public static void main(String[] args) {
    int ip = toInt("192.168.10.77");
    int prefix = 26;
    int mask = prefix == 0 ? 0 : -1 << (32 - prefix);
    int network = ip & mask;
    int broadcast = network | ~mask;
    System.out.println("network   " + toText(network));
    System.out.println("broadcast " + toText(broadcast));
    System.out.println("hosts     " + ((1L << (32 - prefix)) - 2));
  }
}
Read the full lesson