Java Reference
In-Depth Information
work interface, such as the loopback interface. Each interface has an operating sys-
tem-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, eth0 or en0 for the first Ether-
net on systems that hide the details of the card manufacturer, or de0 and de1 for the first and
second Digital Equipment [ 51 ] DC21x4x-based Ethernet card, xl0 for a 3Com EtherLink XL,
and so on. The loopback interface is almost invariably lo0 on all 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 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 Net-
workInterface 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 16-15 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 laptop , 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 16-15. NetworkInterfaceDemo.java
public
public class
class NetworkInterfaceDemo
NetworkInterfaceDemo {
public
public static
throws IOException {
Enumeration list = NetworkInterface . getNetworkInterfaces ();
while
static void
void main ( String [] a ) throws
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
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 ( "laptop" );
try
try {
NetworkInterface dest = NetworkInterface . getByInetAddress ( destAddr );
System . out . println ( "Address for " + destAddr + " is " + dest );
} catch
catch ( SocketException ex ) {
System . err . println ( "Couldn't get address for " + destAddr );
}
 
Search WWH ::




Custom Search