How to get subnet mask of local system using java?
Asked Answered
P

9

26

How do you get the Subnet mask address of the local system using Java?

Parsonage answered 3/8, 2009 at 10:0 Comment(0)
S
31

the netmask of the first address of the localhost interface:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();

a more complete approach:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
    System.out.println(address.getNetworkPrefixLength());
}

/24 means 255.255.255.

Sisal answered 3/8, 2009 at 10:20 Comment(2)
Typical IPv4 values would be 8 (255.0.0.0), 16 (255.255.0.0) or 24 (255.255.255.0).Irade
"/24 means 255.255.255.000" ?Disconformity
O
7

I found that:

NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

To get subnetmask for ipv6 we can use:

 networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength(); 

To get subnetmask for ipv4 we can use:

networkInterface.getInterfaceAddresses().get(1).getNetworkPrefixLength();
Ossuary answered 10/1, 2013 at 9:2 Comment(0)
L
6

You can convert the ipv4 obtained value into the standard textual ipv4 format like this:

short prflen=...getNetworkPrefixLength();
int shft = 0xffffffff<<(32-prflen);
int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
String submask = oct1+"."+oct2+"."+oct3+"."+oct4;
Lialiabilities answered 13/10, 2015 at 5:12 Comment(0)
L
5

java.net.InterfaceAddress in SE6 has a getNetworkPrefixLength method that returns, as the name suggests, the network prefix length. You can calculate the subnet mask from this if you would rather have it in that format. java.net.InterfaceAddress supports both IPv4 and IPv6.

getSubnetMask() in several network application APIs returns subnet mask in java.net.InetAddress form for specified IP address (a local system may have many local IP addresses)

Loesceke answered 3/8, 2009 at 10:5 Comment(1)
Do you have any idea about to get DNS and default gateway from Ethernet in Android?Goldin
I
4

I devised an IPv4 only solution that is simple enough. I needed that to generate netmask for subnetworks here in order to delegate those subnets correctly. I know I could have generated a table of the 32 possible masks, but I prefered to get it computed each time.

So here is my solution.

/*
 * Get network mask for the IP address and network prefix specified...
 * The network mask will be returned has an IP, thus you can
 * print it out with .getHostAddress()...
 */
public static InetAddress getIPv4LocalNetMask(InetAddress ip, int netPrefix) {

    try {
        // Since this is for IPv4, it's 32 bits, so set the sign value of
        // the int to "negative"...
        int shiftby = (1<<31);
        // For the number of bits of the prefix -1 (we already set the sign bit)
        for (int i=netPrefix-1; i>0; i--) {
            // Shift the sign right... Java makes the sign bit sticky on a shift...
            // So no need to "set it back up"...
            shiftby = (shiftby >> 1);
        }
        // Transform the resulting value in xxx.xxx.xxx.xxx format, like if
        /// it was a standard address...
        String maskString = Integer.toString((shiftby >> 24) & 255) + "." + Integer.toString((shiftby >> 16) & 255) + "." + Integer.toString((shiftby >> 8) & 255) + "." + Integer.toString(shiftby & 255);
        // Return the address thus created...
        return InetAddress.getByName(maskString);
    }
        catch(Exception e){e.printStackTrace();
    }
    // Something went wrong here...
    return null;
}

You just call it with the IP and the prefix you want to use, it will generate the netmask for you.

Ioab answered 10/9, 2010 at 16:24 Comment(0)
H
2

I just finished working on an API for subnetting networks with Java.

https://launchpad.net/subnettingapi

it has that functionality and more.

Humorist answered 25/11, 2010 at 7:55 Comment(0)
D
2

Here is an answer, how to get a submask from WIFI connection: link

I adapted it for my needs, and here it is:

private static String intToIP(int ipAddress) {
    String ret = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
            (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
            (ipAddress >> 24 & 0xff));

    return ret;
}

public static String GetSubnetMask_WIFI() {

    WifiManager wifiManager = (WifiManager) Global.getMainActivity()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    DhcpInfo dhcp = wifiManager.getDhcpInfo();
    String mask = intToIP(dhcp.netmask);

    return mask;
}
Deerhound answered 15/1, 2013 at 0:11 Comment(1)
This is android specific, which the question did not specify.Gambit
V
2

In summary, a method to obtain the mask would be like this:

public String mascara() throws SocketException{
    try{
        InetAddress localHost = Inet4Address.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
        prefijo = 
            ""+networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
        int shft = 0xffffffff<<(32- 
                networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength());
        int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
        int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
        int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
        int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
        mascara = oct1+"."+oct2+"."+oct3+"."+oct4;
        // System.out.println(""+mascara);           
    }catch(UnknownHostException e){
        System.out.println("Error: "+e);
    }
    return mascara;
}
Velure answered 25/10, 2018 at 20:31 Comment(1)
Hola Israel, aquí en Stack Overflow sólo se permite el inglés, sí hablas solo castellano a lo mejor te interesa el Stack Overflow en españolOpalina
L
1

FWIW, in the past I'd tried using InterfaceAddress.getNetworkPrefixLength() and InterfaceAddress.getBroadcast(), but they don't return accurate info (this is on Windows, with Sun JDK 1.6.0 update 10). The network prefix length is 128 (not 24, which it is on my network), and the broadcast address returned is 255.255.255.255 (not 192.168.1.255, which it is on my network).

James

Update: I just found the solution posted here:

     http://forums.sun.com/thread.jspa?threadID=5277744

You need to prevent Java from using IPv6, so that it isn't getting to IPv4 via IPv6. Adding -Djava.net.preferIPv4Stack=true to the command line fixes the results from InterfaceAddress.getNetworkPrefixLength() and InterfaceAddress.getBroadcast() for me.

Loats answered 22/8, 2009 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.