Java Reference
In-Depth Information
}
}
Here's the result:
%
java OReillyByName
www.oreilly.com/208.201.239.36
You can also do a reverse lookup by IP address. For example, if you want the hostname
for the address 208.201.239.100, pass the dotted quad address to
InetAddress.getBy
Name()
:
InetAddress address = InetAddress.getByName("208.201.239.100");
System.out.println(address.getHostName());
If the address you look up does not have a hostname,
getHostName()
simply returns
the dotted quad address you supplied.
I mentioned earlier that
www.oreilly.com
actually has two addresses. Which one
getHostName()
returns is indeterminate. If, for some reason, you need all the addresses
of a host, call
getAllByName()
instead, which returns an array:
try
{
InetAddress
[]
addresses
=
InetAddress
.
getAllByName
(
"www.oreilly.com"
);
for
(
InetAddress
address
:
addresses
)
{
System
.
out
.
println
(
address
);
}
}
catch
(
UnknownHostException
ex
)
{
System
.
out
.
println
(
"Could not find www.oreilly.com"
);
}
Finally, the
getLocalHost()
method returns an
InetAddress
object for the host on
which your code is running:
InetAddress
me
=
InetAddress
.
getLocalHost
();
This method tries to connect to DNS to get a real hostname and IP address such as
“elharo.laptop.corp.com” and “192.1.254.68”; but if that fails it may return the
loop‐
back
address instead. This is the hostname “localhost” and the dotted quad address
“127.0.0.1”.
Example 4-2
prints the address of the machine it's run on.
Example 4-2. Find the address of the local machine
import
java.net.*
;
public
class
MyAddress
{
public
static
void
main
(
String
[]
args
)
{
try
{
InetAddress
address
=
InetAddress
.
getLocalHost
();
System
.
out
.
println
(
address
);