List IP addresses in Java
This article explains what a network interface is and presents code to list IP addresses bound to physical interfaces in Java.
A computer connects to a network through a connection point called a Network Interface. A network interface can be a physical hardware like your ethernet card or a wireless network card (WiFi module); or it can be implemented in software with no physical form, like your loopback interface bearing a special IP – 127.0.0.1. Either case, a network interface allows a computer to connect to a network and communicate with other computers on a network. A network interface has an associated name and one or more IP addresses.
JDK provides java.net.NetworkInterface class that represents a network interface both physical and virtual. The NetworkInterface class has no public constructor and hence you cannot instantiate the class. Instead, it provides static factory method getNetworkInterfaces() that returns the list of all interfaces on the computer. Each object in the list is an instance of NetworkInterface class that represents an interface.
Apart from getNetworkInterfaces() method, there are other factory methods like getByInetAddress() and getByName() to get instance by IP address bound to the interface or by the interface name respectively.
Below is the code to list the IP addresses bound to a physical network interfaces in Java. The code below discards the virtual interfaces and the loopback interface and lists IP addresses bound, only to physical interfaces.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class IPLister { public static void main(String[] args) { listIPAddresses(); } private static void listIPAddresses(){ Enumeration<NetworkInterface> net = null; try { // get all interfaces; ethernet, wifi, virtual... etc net = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { throw new RuntimeException(e); } if (net == null){ throw new RuntimeException("No network interfaces found."); } while(net.hasMoreElements()){ NetworkInterface element = net.nextElement(); try { if (element.isVirtual() || element.isLoopback()){ // discard virtual and loopback interface (127.0.0.1) continue; } // rest are either Wifi or ethernet interfaces // loop through and print the IPs Enumeration<InetAddress> addresses = element.getInetAddresses(); while (addresses.hasMoreElements()){ InetAddress ip = addresses.nextElement(); if (ip instanceof Inet4Address){ if (ip.isSiteLocalAddress()){ System.out.println(element.getDisplayName() + " - " + ip.getHostAddress()); } } } } catch (SocketException e) { e.printStackTrace(); } } } // listIPAddresses() ends } |