Working with Network Interfaces
in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
java.net.NetworkInterface
ClassNetworkInterface
Objects:
NetworkInterface.getNetworkInterfaces()
methodgetSubinterface()
and getParent()
retrieve subinterfaces (a.k.a., virtual interfaces) and
parent interfaces respectivelyimport java.io.*; import java.net.*; import java.util.*; /** * An application that displays all of the network interfaces * on this computer. * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class DisplayNIFs { /** * The entry point of the application. * * @param args Command line arguments (-r for a recursive display) */ public static void main(String[] args) { Enumeration<NetworkInterface> nifs; String indent; indent = ""; if ((args != null) && (args.length > 0) && args[0].equals("-r")) indent = " "; try { display(NetworkInterface.getNetworkInterfaces(), indent); } catch (SocketException se) { System.out.println("Unable to get network interfaces!"); } } /** * Display the names of an Enumeration of NetworkInterface objects. * * @param nifs The Enumeration * @param indent The indentation String ("" for none and no recursion) */ private static void display(Enumeration<NetworkInterface> nifs, String indent) throws SocketException { while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); System.out.printf("%s%s (%s)\n", indent, nif.getDisplayName(), nif.getName()); if (!indent.equals("")) display(nif.getSubInterfaces(), indent+"\t"); System.out.println(); } } }
import java.io.*; import java.net.*; import java.util.*; /** * An application that displays all of the network addresses * on this computer. * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class DisplayAddresses { /** * The entry point of the application. * * @param args Command line arguments (ignored) */ public static void main(String[] args) { Enumeration<NetworkInterface> nifs; try { display(NetworkInterface.getNetworkInterfaces()); } catch (SocketException se) { System.out.println("Unable to get network interfaces!"); } } /** * Display the addresses of an Enumeration of NetworkInterface objects. * * @param nifs The Enumeration * @param indent The indentation String ("" for none and no recursion) */ private static void display(Enumeration<NetworkInterface> nifs) throws SocketException { while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); System.out.printf("%s (%s)\n", nif.getDisplayName(), nif.getName()); Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { System.out.printf("\t%s\n", addresses.nextElement()); } System.out.println(); } } }
getHardwareAddress()
returns the hardware
(e.g., MAC for Ethernet) addressgetMTU()
returns the maximum transmision unitisLoopback()
isUp()
isVirtual()
supportsMulticast()