InetAddress Class in Networking
InetAddress:
The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. You interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address. The InetAddress class hides the number inside. InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods:
The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. Factory methods are merely a convention whereby static methods in a class return an instance of that class. Three commonly used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException static InetAddress getByName(String hostName) throws UnknownHostException static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The [java]getLocalHost()[/java] method simply returns the InetAddress object that represents the localhost. The [java]getByName()[/java] method returns an InetAddress for a hostname passed to it. If these methods are unable to resolve the hostname, they throw an [java]UnknownHostException[/java].
The [java]getAllByName()[/java] factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It will also throw an [java]UnknownHostException[/java] if it can’t resolve the name to at least one address. InetAddress also includes the factory method [java]getByAddress()[/java], which takes an IP address and returns an InetAddress object.
Demonstrate InetAddress Program:
import java.net.*; class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address); Address = InetAddress.getByName("webeduclick.com"); System.out.println(Address); InetAddress SW[] = InetAddress.getAllByName("www.forbes.com"); for (int i=0; i<SW.length; i++) System.out.println(SW[i]); } }