views:

486

answers:

2

Given a CIDR address, e.g. 192.168.10.0/24

  • How to determine mask length? (24)
  • How to determine mask address? (255.255.255.0)
  • How to determine network address? (192.168.10.0)
+1  A: 

The algorithm is in pseudo code (actually PHP), you can translate it to java yourself.
Algoritm from here.

//$ipNetmask = "192.168.1.12/30";
list($ip, $netmask) = split( "/", $ipNetmask );
$ip_elements_decimal = split( "[.]", $ip );
$netmask_result="";
for($i=1; $i <= $netmask; $i++) {
  $netmask_result .= "1";
}
for($i=$netmask+1; $i <= 32; $i++) {
    $netmask_result .= "0";
}
$netmask_ip_binary_array = str_split( $netmask_result, 8 );
$netmask_ip_decimal_array = array();
foreach( $netmask_ip_binary_array as $k => $v ){
    $netmask_ip_decimal_array[$k] = bindec( $v ); // "100" => 4
    $network_address_array[$k] = ( $netmask_ip_decimal_array[$k] & $ip_elements_decimal[$k] );
}
$network_address = join( ".", $network_address_array );

// ------------------------------------------------
           // TCP/IP NETWORK INFORMATION
// ------------------------------------------------
// IP Entered = ..................: 192.168.1.12
// CIDR = ........................: /30
// Netmask = .....................: 255.255.255.252
// Network Address = .............: 192.168.1.12

// Broadcast Address = ...........: 192.168.1.15
// Usable IP Addresses = .........: 2
// First Usable IP Address = .....: 192.168.1.13
// Last Usable IP Address = ......: 192.168.1.14
clyfe
+1  A: 

This is how you would do it in Java,

    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());
ZZ Coder