One of the classes within package java.net is called InetAddress , which handles Internet addresses both as host names and as IP addresses. Static method getByName of this class uses DNS (Domain Name System) to return the Internet address of a specifi ed host name as an InetAddress object. In order to display the IP address from this object, we can simply use method println (which will cause the object’s toString method to be executed). Since method getByName throws the checked exception UnknownHostException if the host name is not recognised, we must either throw this exception or (preferably) handle it with a catch clause. The following example illustrates this.
Exampleimport java.net.*;
import java.util.*;
public class IPFinder
{
public static void main(String[] args)
{
String host;
Scanner input = new Scanner(System.in);
InetAddress address;
System.out.print("\n\nEnter host name: ");
host = input.next();
try
{
address = InetAddress.getByName(host);
System.out.println("IP address: "
+ address.toString());
}
catch (UnknownHostException uhEx)
{
System.out.println("Could not fi nd " + host);
}
}
}
No comments:
Post a Comment