ProblemYou wish to find out about the computer's networking arrangements. SolutionUse the NetworkInterface class introduced in JDK 1.4. DiscussionEvery computer on a network has one or more network interfaces. On typical desktop machines, a network interface represents a network card or network port and often some software network interfaces, such as the loopback interface. Each interface has an operating system-defined name. On most versions of Unix, these devices have a two- or three-character device driver name plus a digit (starting from 0); for example, de0 and de1 for the first and second Digital Equipment[3] DC21x4x-based Ethernet card, xl0 for a 3Com EtherLink XL, and so on. On Linux, these interfaces are typically named eth0, eth1, and so on, without regard for the manufacturer. The loopback interface is usually lo0, at least on Unix-like platforms.
So what? Most of the time this is of no consequence to you. If you have only one network connection, like a dialup or cable link to your ISP, you really don't care. Where this matters is on a server, where you might need to find the address for a given network, for example. The NetworkInterface class lets you find out. It has static methods for listing the interfaces and other methods for finding the addresses associated with a given interface. The program in Example 17-14 shows some examples of using this class. Running it prints the names of all the local interfaces. If you happen to be on a computer named daroad, it prints the machine's network address; if not, you probably want to change it to accept the local computer's name from the command line; this is left as an exercise for the reader. Example 17-14. NetworkInterfaceDemo.java/** * Show some uses of the new-in-1.4 NetworkInterface class. */ public class NetworkInterfaceDemo { public static void main(String[] a) throws IOException { Enumeration list = NetworkInterface.getNetworkInterfaces( ); while (list.hasMoreElements( )) { // Get one NetworkInterface NetworkInterface iface = (NetworkInterface) list.nextElement( ); // Print its name System.out.println(iface.getDisplayName( )); Enumeration addrs = iface.getInetAddresses( ); // And its address(es) while (addrs.hasMoreElements( )) { InetAddress addr = (InetAddress) addrs.nextElement( ); System.out.println(addr); } } // Try to get the Interface for a given local (this machine's) address InetAddress destAddr = InetAddress.getByName("daroad"); try { NetworkInterface dest = NetworkInterface.getByInetAddress(destAddr); System.out.println("Address for " + destAddr + "" is " + dest); } catch (SocketException ex) { System.err.println("Couldn't get address for " + destAddr); } } } |