dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jul 5, 2021

Java: How to List All Network Interfaces

In our newest Java programming tutorial we learn how to list all of the networking interfaces connected to a socket using the Java packages java.net and java.util. We are searching specifically for any network interfaces available in the system.

We begin by importing java.net and java.util before creating a public class that will handle the utilities we use to scan for network interfaces on the system. Here is how to scan for network interfaces in Java:

*/

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

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

	private void proceed()  
	{
		int networkInterfaceIndex = 0;
        try 
		{
            Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) 
			{
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
				System.out.println("Network interface " + ++networkInterfaceIndex + ": "+ networkInterface.getName());
            }
        }catch(SocketException socketException) 
		{
            socketException.getMessage();
        }
	}
}

/*

Note: The output of running this code will vary depending upon your system. An example of the output you can expect is included below:

[root@mypc]# java ListAllNetworkInterfaces
Network interface 1: lo
Network interface 2: net0
Network interface 3: eth0
Network interface 4: eth1
Network interface 5: net1
Network interface 6: eth2
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date