Java Reference
In-Depth Information
}
}
Here's the result of running this on the IBiblio login server:
%
java InterfaceLister
name:eth1 (eth1) index: 3 addresses:
/192.168.210.122;
name:eth0 (eth0) index: 2 addresses:
/152.2.210.122;
name:lo (lo) index: 1 addresses:
/127.0.0.1;
You can see that this host has two separate Ethernet cards plus the local loopback address.
The Ethernet card with index 2 has the IP address 152.2.210.122. The Ethernet card
with index 3 has the IP address 192.168.210.122. The loopback interface has address
127.0.0.1, as always.
Getter Methods
Once you have a
NetworkInterface
object, you can inquire about its IP address and
name. This is pretty much the only thing you can do with these objects.
public Enumeration getInetAddresses()
A single network interface may be bound to more than one IP address. This situation
isn't common these days, but it does happen. The
getInetAddresses()
method returns
a
java.util.Enumeration
containing an
InetAddress
object for each IP address the
interface is bound to. For example, this code fragment lists all the IP addresses for the
eth0 interface:
NetworkInterface
eth0
=
NetworkInterrface
.
getByName
(
"eth0"
);
Enumeration
addresses
=
eth0
.
getInetAddresses
();
while
(
addresses
.
hasMoreElements
())
{
System
.
out
.
println
(
addresses
.
nextElement
());
}
public String getName()
The
getName()
method returns the name of a particular
NetworkInterface
object, such
as eth0 or lo.
public String getDisplayName()
The
getDisplayName()
method allegedly returns a more human-friendly name for the
particular
NetworkInterface
—something like “Ethernet Card 0.” However, in my tests
on Unix, it always returned the same string as
getName()
. On Windows, you may see
slightly friendlier names such as “Local Area Connection” or “Local Area Connection
2.”