Java Reference
In-Depth Information
Example 4-7. Are www.ibiblio.org and helios.ibiblio.org the same?
import
java.net.*
;
public
class
IBiblioAliases
{
public
static
void
main
(
String
args
[])
{
try
{
InetAddress
ibiblio
=
InetAddress
.
getByName
(
"www.ibiblio.org"
);
InetAddress
helios
=
InetAddress
.
getByName
(
"helios.ibiblio.org"
);
if
(
ibiblio
.
equals
(
helios
))
{
System
.
out
.
println
(
"www.ibiblio.org is the same as helios.ibiblio.org"
);
}
else
{
System
.
out
.
println
(
"www.ibiblio.org is not the same as helios.ibiblio.org"
);
}
}
catch
(
UnknownHostException
ex
)
{
System
.
out
.
println
(
"Host lookup failed."
);
}
}
}
When you run this program, you discover:
%
java IBiblioAliases
www.ibiblio.org is the same as helios.ibiblio.org
The
hashCode()
method is consistent with the
equals()
method. The
int
that
hash
Code()
returns is calculated solely from the IP address. It does not take the hostname
into account. If two
InetAddress
objects have the same address, then they have the
same hash code, even if their hostnames are different.
Like all good classes,
java.net.InetAddress
has a
toString()
method that returns a
short text representation of the object.
Example 4-1
and
Example 4-2
implicitly called
this method when passing
InetAddress
objects to
System.out.println()
. As you saw,
the string produced by
toString()
has the form:
hostname/dotted quad address
Not all
InetAddress
objects have hostnames. If one doesn't, the dotted quad address is
substituted in Java 1.3 and earlier. In Java 1.4 and later, the hostname is set to the empty
string.
Inet4Address and Inet6Address
Java uses two classes,
Inet4Address
and
Inet6Address
, in order to distinguish IPv4
addresses from IPv6 addresses:
public
final
class
Inet4Address
extends
InetAddress
public
final
class
Inet6Address
extends
InetAddress