Calculate CIDR from a given netmask - Java
Asked Answered
C

3

8

Is there a way to calculate a CIDR given a Sub net mask using any Java lib/function/trick?? I have been looking for a while and all I can find is from CIDR -> Netmask and I need it the other way arround Netmask -> CIDR ... Im not that handy on Java, but im willing to read a lot =) thnx guys

PzP =)

Chemash answered 23/10, 2013 at 1:52 Comment(0)
L
9

Whipped up a quick example. This converts an InetAddress into a cidr value, it also validates that the InetAddress represents a valid netmask.

The test input is 255.255.128.0. The output cidr is 17.

package com.stackoverflow._19531411;

import java.net.InetAddress;


public class NetmaskToCIDR {


    public static int convertNetmaskToCIDR(InetAddress netmask){

        byte[] netmaskBytes = netmask.getAddress();
        int cidr = 0;
        boolean zero = false;
        for(byte b : netmaskBytes){
            int mask = 0x80;

            for(int i = 0; i < 8; i++){
                int result = b & mask;
                if(result == 0){
                    zero = true;
                }else if(zero){
                    throw new IllegalArgumentException("Invalid netmask.");
                } else {
                    cidr++;
                }
                mask >>>= 1;
            }
        }
        return cidr;
    }

    public static void main(String[] args) throws Exception {

        InetAddress netmask = InetAddress.getByName("255.255.128.0");

        System.out.println(convertNetmaskToCIDR(netmask));

    }
}

Credit for psuedocode @ https://mcmap.net/q/1328147/-determine-if-net-mask-is-valid-in-java

Lifeblood answered 23/10, 2013 at 2:21 Comment(0)
B
1

You can use the toCidrNotation function in the Apache SubnetUtils module to do this. Here's a Java example.

Builder answered 23/10, 2013 at 1:56 Comment(0)
T
0

Have a look at the Apache Net Jar (Class SubnetUtils) http://commons.apache.org/proper/commons-net/download_net.cgi

Also in a project that I was doing we used the excellent Postgres DB functions which also supported IPV6 http://www.postgresql.org/docs/8.1/static/functions-net.html

http://commons.apache.org/proper/commons-net/javadocs/api-3.3/index.html

Tokay answered 23/10, 2013 at 1:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.