How do you get the Subnet
mask address of the local system using Java?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With