Java Reference
In-Depth Information
Most of the time, you can use hostnames and let DNS handle the translation to IP
addresses. As long as you can connect to a domain name server, you don't need to worry
about the details of how names and addresses are passed between your machine, the
local domain name server, and the rest of the Internet. However, you will need access
to at least one domain name server to use the examples in this chapter and most of the
rest of this topic. These programs will not work on a standalone computer. Your machine
must be connected to the Internet.
The InetAddress Class
The
java.net.InetAddress
class is Java's high-level representation of an IP address,
both IPv4 and IPv6. It is used by most of the other networking classes, including
Socket
,
ServerSocket
,
URL
,
DatagramSocket
,
DatagramPacket
, and more. Usually, it includes
both a hostname and an IP address.
Creating New InetAddress Objects
There are no public constructors in the
InetAddress
class. Instead,
InetAddress
has
static factory methods that connect to a DNS server to resolve a hostname. The most
common is
InetAddress.getByName()
. For example, this is how you look up
www.oreilly.com
:
InetAddress
address
=
InetAddress
.
getByName
(
"www.oreilly.com"
);
This method does not merely set a private
String
field in the
InetAddress
class. It
actually makes a connection to the local DNS server to look up the name and the numeric
address. (If you've looked up this host previously, the information may be cached locally,
in which case a network connection is not required.) If the DNS server can't find the
address, this method throws an
UnknownHostException
, a subclass of
IOException
.
Example 4-1
shows a complete program that creates an
InetAddress
object for
www.oreilly.com
including all the necessary imports and exception handling.
Example 4-1. A program that prints the address of www.oreilly.com
import
java.net.*
;
public
class
OReillyByName
{
public
static
void
main
(
String
[]
args
)
{
try
{
InetAddress
address
=
InetAddress
.
getByName
(
"www.oreilly.com"
);
System
.
out
.
println
(
address
);
}
catch
(
UnknownHostException
ex
)
{
System
.
out
.
println
(
"Could not find www.oreilly.com"
);
}