Search code examples
javanetwork-programmingnetwork-interface

How Do I Get Ip Configuration From Network Interface


I have a java application that pulls information from network interface and I'm using NetworkInterface class to iterate through the gazillion of interfaces I have in my computer. "I have installed virtualbox" and this create many virtual interface. But I need to get info from my wireless or ethernet interface as those are the only option to connect to the network. The problem is that I want to be able to sort through all these interfaces and get only the relevant. What approach you guys suggest? doing a search through the NetworkInteface collection looking for eth0 or wlan1. any ideas appreciated. Here's the code that deals with network interface in my application.

//displaying all network interface 
Enumeration<NetworkInterface> nets = null;
try {
   nets = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e3) {
    e3.printStackTrace();
}

for (NetworkInterface netint : Collections.list(nets)) {            
   displayInterfaceInformation(netint);
}

static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { 
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    System.out.printf(count + " Display name: %s\n", netint.getDisplayName());
    System.out.printf("Name: %s\n", netint.getName());
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {           
        System.out.printf("InetAddress: %s\n", inetAddress);
    }
    System.out.println("\n");
}

Solution

  • There could be a more straightforward way, but if you're just looking for the interface that connects to the internet, there's a simple trick you can use that doesn't involve reading routing tables - just create a socket, connect it to an address that exists on the internet, then get that socket's local address. It's better to use a UDP socket since its connect doesn't do any actual IO:

    DatagramSocket s = new DatagramSocket();
    s.connect(InetAddress.getByName("1.1.1.1"), 53);
    System.out.println(s.getLocalAddress());
    

    The operating system will bind the socket to an appropriate interface for the outbound connection using the routing table. Once you have the IP address, you can find the interface with that IP address.