How to get subnet mask of local system using java?

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


Solution 1:

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.

Solution 2:

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)

Solution 3:

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

Solution 4:

You can convert the obtained value into the standard textual 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;