The InetAddress Class
The
java.net.InetAddress
class is Java’s encapsulation of an
IP address. It is used by most of the other networking classes,
including Socket
, ServerSocket
,
URL
, DatagramSocket
,
DatagramPacket
, and more.
public final class InetAddress extends Object implements Serializable
This class represents an Internet address as two fields:
hostName
(a String
) and
address
(an int
).
hostName
contains the name of the host; for
example, www.oreilly.com.
address
contains the 32-bit IP address. These
fields are not public, so you can’t access them directly. It
will probably be necessary to change this representation to a byte
array when 16-byte IPv6 addresses come into use. However, if you
always use the InetAddress
class to represent
addresses, the changeover should not affect you; the class shields
you from the details of how addresses are implemented.
Creating New InetAddress Objects
There are no public constructors in
the InetAddress
class. However,
InetAddress
has three static methods that return
suitably initialized InetAddress
objects, given a
little information. They are:
public static InetAddress InetAddress.getByName(String hostName) throws UnknownHostException public static InetAddress[] InetAddress.getAllByName(String hostName) throws UnknownHostException public static InetAddress InetAddress.getLocalHost( ) throws UnknownHostException
All three of these may make a connection to the local DNS server to
fill out the information in the InetAddress
object. This has a ...
Get Java Network Programming, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.