dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Get all the IP Addresses to Which a Device is Exposed

Learn how to identify various interfaces and the related IP configuration available on them.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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

*/ 

 

Visit the DevX Tip Bank

 





   
Srinath M. S. says: "I would love to leave a footprint in this flat world."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date