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 NetworkInterfaceIPsAvailable IPs in NetworkInterface.IP: 127.0.0.1IP: 134.220.154.89*/