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.

 


 

Leave a Reply

avatar
300
  Subscribe  
Notify of