Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IPv4 addresses of an ethernet adapter in Windows using Java 1.5

Problem

My Windows system has multiple ethernet adapters. Given the name of an ethernet adapter, I need to find its IP addresses.

For example, the output of ipconfig command of my system is:

Ethernet adapter GB1:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 0.0.0.0
   Subnet Mask . . . . . . . . . . . : 0.0.0.0
   Default Gateway . . . . . . . . . : 

Ethernet adapter SWITCH:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 10.200.1.11
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   IP Address. . . . . . . . . . . . : 10.200.1.51
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 

Ethernet adapter LAN:

   Connection-specific DNS Suffix  . : 
   IP Address. . . . . . . . . . . . : 10.1.2.62
   Subnet Mask . . . . . . . . . . . : 255.255.254.0
   IP Address. . . . . . . . . . . . : 10.1.2.151
   Subnet Mask . . . . . . . . . . . : 255.255.254.0
   Default Gateway . . . . . . . . . : 10.1.2.1

Note: I need not bother about wireless adapters or any other kind of adapters. I need to do this for ethernet adapters only.

For this system, I need to write a Java class that behaves as shown below:

C:>java NameToIp GB1
0.0.0.0

C:>java NameToIp SWITCH
10.200.1.11
10.200.1.51

C:>java NameToIp LAN
10.1.2.62
10.1.2.151

What doesn't work

Using java.net.NetworkInterface didn't help. It's getName() and getDisplayName() methods don't print the adapter connection names as it appears in the output of ipconfig or in Windows Network Connections. They print the actual device names instead. For example, consider the following code:

import java.util.Enumeration;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ListInterfaces 
{
    public static void main(String[] args) throws SocketException, UnknownHostException {

        Enumeration<NetworkInterface> nwInterfaces = NetworkInterface.getNetworkInterfaces();

        while (nwInterfaces.hasMoreElements()) {

            NetworkInterface nwInterface = nwInterfaces.nextElement();
            System.out.print(nwInterface.getName() + ": " +
                             nwInterface.getDisplayName());

            Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                System.out.print(" - " + address.getHostAddress());
            }
            System.out.println();
        }
    }
}

This prints the following output:

C:>java ListInterfaces
lo: MS TCP Loopback interface - 127.0.0.1
eth0: Broadcom BCM5709C NetXtreme II GigE (NDIS VBD Client) # 
eth1: Broadcom BCM5709C NetXtreme II GigE (NDIS VBD Client) #2 - 10.200.1.11 - 10.200.1.51
eth2: Broadcom BCM5709C NetXtreme II GigE (NDIS VBD Client) #3 - 10.1.2.62 - 10.1.2.151

An ugly hack that works

I have written an ugly hack that extracts the IP addresses of the specified adapter name from the output of ipconfig. Here is the code.

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.IOException;

public class NameToIp
{
    public static ArrayList<String> getIP(String adapterName)
    throws IOException, InterruptedException
    {
        // Run the Windows 'ipconfig' command and get its stdout
        ProcessBuilder cmdBuilder = new ProcessBuilder("ipconfig");
        Process process = cmdBuilder.start();
        BufferedReader stdout = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        // Find the section for the specified adapter
        String line;
        boolean foundAdapter = false;
        while ((line = stdout.readLine()) != null) {
            line = line.trim();
            if (line.equals("Ethernet adapter " + adapterName + ':')) {
                foundAdapter = true;
                break;
            }
        }
        if (!foundAdapter) {
            process.waitFor();
            throw new IOException("Adapter not found");
        }

        // Find IP addresses in the found section
        ArrayList<String> ips = new ArrayList<String>();
        while ((line = stdout.readLine()) != null) {
            // Stop parsing if we reach the beginning of the next
            // adapter section in the output of ifconfig
            if (line.length() > 0 && line.charAt(0) != ' ') {
                break;
            }

            line = line.trim();

            // Extract IP addresses
            if (line.startsWith("IP Address.") ||
                line.startsWith("IPv4 Address.")) {

                int colonIndex;
                if ((colonIndex = line.indexOf(':')) != 1) {
                    ips.add(line.substring(colonIndex + 2));
                }
            }
        }
        process.waitFor();

        return ips;
    }

    public static void main(String[] args)
    throws IOException, InterruptedException
    {
        // Print help message if adapter name has not been specified
        if (args.length != 1) {
            StackTraceElement[] stack = Thread.currentThread().getStackTrace();
            String prog = stack[stack.length - 1].getClassName();

            System.err.println("Usage: java " + prog + " ADAPTERNAME");
            System.err.println("Examples:");
            System.err.println("  java " + prog +" \"Local Area Connection\"");
            System.err.println("  java " + prog +" LAN");
            System.err.println("  java " + prog +" SWITCH");
            System.exit(1);
        }

        ArrayList<String> ips = getIP(args[0]);
        for (String ip: ips) {
            System.out.println(ip);
        }
    } 
}

Question

Is there a better way to solve this problem?

like image 868
Susam Pal Avatar asked Oct 09 '12 14:10

Susam Pal


People also ask

How do I find my Java IP address?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.


1 Answers

Create a dll that uses the Windows API to query the local ethernet address and use JNI to invoke the dll.

like image 146
SpaceTrucker Avatar answered Oct 06 '22 00:10

SpaceTrucker