dcsimg
 

Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Tuesday Oct 23rd 2018 by M S Sridhar

Language: Java, Expertise: Intermediate - Learn how to identify various interfaces and the related IP configuration available on them.

At times, your device can be exposed using multiple interface cards. The following code sample will help identify various interfaces and the related IP configuration available on them.

import java.net.*;
import java.util.*;

public class NetworkInterfaceIPs 
{
   public static void main(String args[])
   {
      NetworkInterfaceIPs networkInterfaceIPs = new NetworkInterfaceIPs();
      networkInterfaceIPs.proceed();
   }

   private void proceed() 
   {
      try
      {
         Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
         InetAddress inetAddress = null;
         System.out.println("Available IPs in NetworkInterface.");
         while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
                Enumeration inetAddresses = networkInterface.getInetAddresses();
            
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address) { //Working on only IPv4 IPs
                  System.out.println("IP: " + inetAddress.getHostAddress());
                    }
               
                }
            }         
      }catch(SocketException se)
      {
         System.out.println("SocketException: " + se);
      }
   }
}

/*

Expected output:

[root@mypc]# java NetworkInterfaceIPs
Available IPs in NetworkInterface.
IP: 127.0.0.1
IP: 134.220.154.89

*/ 
Home
Mobile Site | Full Site