Getting network interface information in Java

In my Android application, I’ll need to find out which network interfaces are available and which IP addresses they have. Turns out the necessary API is really simple: And being part of it’s not even Android specific. 🙂

There’s a static function to get all active network interfaces:

Enumeration<NetworkInterface> ifs = null;
try {
    ifs = NetworkInterface.getNetworkInterfaces();
} catch (SocketException ex) {
    // error handling appropriate for your application
if (ifs == null)
    // cancel the examination of "ifs"

ifs will be null if there are no active interfaces. Otherwise, just get each interface in turn and read its addresses. For example, you could write them to standard output:

while (ifs.hasMoreElements()) {
    NetworkInterface iface = ifs.nextElement();
    Enumeration<InetAddress> en = iface.getInetAddresses();
    while (en.hasMoreElements()) {
        InetAddress addr = en.nextElement();
        String s = addr.getHostAddress();
        int end = s.lastIndexOf("%");
        if (end > 0)
            System.out.println("\t" + s.substring(0, end));
            System.out.println("\t" + s);

The string modification at the end might seem strange, but without it, IPv6 addresses would be printed with an appended “%X” where X is a number indicating the address scope.

If you want to try this on Android, you could append the addresses to an android.widget.TextView. Note that your application will need the INTERNET permission to read the requested data. Just put the following into the application’s AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

2 thoughts on “Getting network interface information in Java

  1. Hi,
    I was wondering if this will work on 3.0 api 11

    I need to read my current tcp/ip address and programmaticlly change it from DHCP to a static IP.

    1. I haven’t worked with Android 3 yet, but it is a generic Java API, so I think reading the addresses should work the same way. You’ll have to figure out how to change it by yourself, though. 😉

Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: