Java Reference
In-Depth Information
Most of the time, you really shouldn't be concerned with whether an address is an IPv4
or IPv6 address. In the application layer where Java programs reside, you simply don't
need to know this (and even if you do need to know, it's quicker to check the size of the
byte array returned by getAddress() than to use instanceof to test which subclass you
have). Inet4Address overrides several of the methods in InetAddress but doesn't
change their behavior in any public way. Inet6Address is similar, but it does add one
new method not present in the superclass, isIPv4CompatibleAddress() :
public boolean isIPv4CompatibleAddress ()
This method returns true if and only if the address is essentially an IPv4 address stuffed
into an IPv6 container—which means only the last four bytes are nonzero. That is, the
address has the form 0:0:0:0:0:0:0:xxxx . If this is the case, you can pull off the last four
bytes from the array returned by getBytes() and use this data to create an Inet4Ad
dress instead. However, you rarely need to do this.
The NetworkInterface Class
The NetworkInterface class represents a local IP address. This can either be a physical
interface such as an additional Ethernet card (common on firewalls and routers) or it
can be a virtual interface bound to the same physical hardware as the machine's other
IP addresses. The NetworkInterface class provides methods to enumerate all the local
addresses, regardless of interface, and to create InetAddress objects from them. These
InetAddress objects can then be used to create sockets, server sockets, and so forth.
Factory Methods
Because NetworkInterface objects represent physical hardware and virtual addresses,
they cannot be constructed arbitrarily. As with the InetAddress class, there are static
factory methods that return the NetworkInterface object associated with a particular
network interface. You can ask for a NetworkInterface by IP address, by name, or by
enumeration.
public static NetworkInterface getByName(String name) throws SocketException
The getByName() method returns a NetworkInterface object representing the network
interface with the particular name. If there's no interface with that name, it returns null.
If the underlying network stack encounters a problem while locating the relevant net‐
work interface, a SocketException is thrown, but this isn't too likely to happen.
The format of the names is platform dependent. On a typical Unix system, the Ethernet
interface names have the form eth0, eth1, and so forth. The local loopback address is
probably named something like “lo”. On Windows, the names are strings like “CE31”
and “ELX100” that are derived from the name of the vendor and model of hardware on
Search WWH ::




Custom Search