Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get subnet mask of local system using java?

Tags:

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

like image 449
user149621 Avatar asked Aug 03 '09 10:08

user149621


2 Answers

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.

like image 123
dfa Avatar answered Sep 20 '22 12:09

dfa


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)

like image 41
mas Avatar answered Sep 21 '22 12:09

mas