InetAddress
class is a little unusual in that it
doesn't have any public constructors. Instead you pass
the host name or string format of the dotted quad address
to the static InetAddress.getByName()
method like this:
try {
InetAddress utopia = InetAddress.getByName("utopia.poly.edu");
InetAddress duke = InetAddress.getByName("128.238.2.92");
}
catch (UnknownHostException e) {
System.err.println(e);
}
Some hosts have multiple addresses. If you suspect this may be the case
you can return an array of InetAddress
objects with the static InetAddress.getAllByName()
method like this:
import java.net.*;
public class AppleAddresses {
public static void main (String args[]) {
try {
InetAddress[] addresses = InetAddress.getAllByName("www.apple.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException e) {
System.out.println("Could not find www.apple.com");
}
}
}
This prints the following:
www.apple.com/17.254.3.28
www.apple.com/17.254.3.37
www.apple.com/17.254.3.61
www.apple.com/17.254.3.21
Finally the static InetAddress.getLocalHost()
method returns an InetAddress
object that contains the address
of the computer the program is running on.
try {
InetAddress me = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {
System.err.println(e);
}