Java Reference
In-Depth Information
String hostName
=
"www.darwinsys.com"
;
String ipNumber
=
"8.8.8.8"
;
// currently a well-known Google DNS server
// Show getting the InetAddress (looking up a host) by host name
System
.
out
.
println
(
hostName
+
"'s address is "
+
InetAddress
.
getByName
(
hostName
).
getHostAddress
());
// Look up a host by address
System
.
out
.
println
(
ipNumber
+
"'s name is "
+
InetAddress
.
getByName
(
ipNumber
).
getHostName
());
// Look up my localhost addresss
final
final
InetAddress localHost
=
InetAddress
.
getLocalHost
();
System
.
out
.
println
(
"My localhost address is "
+
localHost
);
// Show getting the InetAddress from an open Socket
String someServerName
=
"www.google.com"
;
// assuming there's a web server on the named server:
Socket theSocket
=
new
new
Socket
(
someServerName
,
80
);
InetAddress remote
=
theSocket
.
getInetAddress
();
System
.
out
.
printf
(
"The InetAddress for %s is %s%n"
,
someServerName
,
remote
);
}
}
You can also get an
InetAddress
from a
Socket
by calling its
getInetAddress()
method.
You can construct a
Socket
using an
InetAddress
instead of a hostname string. So, to con-
nect to port number
myPortNumber
on the same host as an existing socket, you'd use:
InetAddress remote = theSocket.getInetAddress( );
Socket anotherSocket = new Socket(remote, myPortNumber);
Finally, to look up all the addresses associated with a host—a server may be on more than
one network—use the static method
getAllByName(host)
, which returns an array of
InetAddress
objects, one for each IP address associated with the given name.
A static method
getLocalHost()
returns an
InetAddress
equivalent to “localhost” or
127.0.0.1. This can be used to connect to a server program running on the same machine as
the client.
If you are using IPv6, you can use
Inet6Address
instead.