Java Reference
In-Depth Information
whether a connection to the named host on the specified port is allowed.) The host
argument may be either a hostname such as www.oreilly.com , a dotted quad IP address
such as 208.201.239.37 , or a hexadecimal IPv6 address such as FEDC::DC:0:7076:10 .
Getter Methods
The InetAddress class contains four getter methods that return the hostname as a string
and the IP address as both a string and a byte array:
public String getHostName ()
public String getCanonicalHostName ()
public byte [] getAddress ()
public String getHostAddress ()
There are no corresponding setHostName() and setAddress() methods, which means
that packages outside of java.net can't change an InetAddress object's fields behind
its back. This makes InetAddress immutable and thus thread safe.
The getHostName() method returns a String that contains the name of the host with
the IP address represented by this InetAddress object. If the machine in question
doesn't have a hostname or if the security manager prevents the name from being de‐
termined, a dotted quad format of the numeric IP address is returned. For example:
InetAddress machine = InetAddress . getLocalHost ();
String localhost = machine . getHostName ();
The getCanonicalHostName() method is similar, but it's a bit more aggressive about
contacting DNS. getHostName() will only call DNS if it doesn't think it already knows
the hostname. getCanonicalHostName() calls DNS if it can, and may replace the ex‐
isting cached hostname. For example:
InetAddress machine = InetAddress . getLocalHost ();
String localhost = machine . getCanonicalHostName ();
The getCanonicalHostName() method is particularly useful when you're starting with
a dotted quad IP address rather than the hostname. Example 4-3 converts the dotted
quad address 208.201.239.37 into a hostname by using InetAddress.getByName() and
then applying getCanonicalHostName() on the resulting object.
Example 4-3. Given the address, find the hostname
import java.net.* ;
public class ReverseTest {
public static void main ( String [] args ) throws UnknownHostException {
InetAddress ia = InetAddress . getByName ( "208.201.239.100" );
System . out . println ( ia . getCanonicalHostName ());
}
}
Search WWH ::




Custom Search