How to query network interfaces and MAC addresses in Java

It's not a big deal, really. However the MAC address is only available since Java6 and to create a Java5 compatible class for working with network interfaces, you've to use the Java reflection API. My demo class might be of help to those who have not yet used reflection. See the attachment for the source of my ListNetworkInterfaces class which will print MAC and IP addresses of all available network interfaces. It'll print MAC addresses only if invoked in a JRE6 (or later). Compilation and invocation is as usually:
javac ListNetworkInterfaces.java
java ListNetworkInterfaces

P.S.: only active interfaces are available through Java ... ie. interfaces that are "up". Eg. on a Debian server only interfaces listed by the plain ifconfig command are available through a call to java.net.NetworkInterface.getNetworkInterfaces(). Interfaces that appear only in the output of ifconfig -a are not listed by getNetworkInterfaces(). Of course, this is most probably JVM and OS dependent.

AttachmentSize
ListNetworkInterfaces.java3.57 KB

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

InetAddress.getLocalHost() and the security manager

In the ListNetworkInterfaces example I also print the "local host address" to stdout. It is quite weakly defined in the Java API spec. what the InetAddress.getLocalHost() call should do. Of course there would be not much sense in returning the loopback address (with IP 127.0.0.1) as you'd expect for "localhost". Smile

In practise the Sun JRE (at least from v5 and higher) returns the "main" address of the local host. By "main" I mean the IP of the hostname that is assigned to the local machine. First it asks for the hostname of the local machine (this comes from the platform specific part -ie. InetAddressImpl- of InetAddress), then it calls an InetAddress.getAddressFromNameService() for that hostname.

However there's also a SecurityManager check to verify whether the running code is allowed to look up the IP address of the hostname of the local host. If that fails, then the loopback address is returned. I'd have better liked an exception to be thrown since you cannot do much with a loopback address. So if you want to get the hostname or IP of the local host, you should always check the result that comes out from InetAddress.getLocalHost() (if the result has the IP of the loopback interface, then the call failed).