By: Grenfel Emailed: 1730 times Printed: 2344 times
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. This is done in lieu of overloading a constructor with various parameter lists when having unique method names makes the results much clearer. In the case of InetAddress, the three methods getLocalHost(), getByName(), and getAllByName() can be used to create instances of InetAddress. These methods are shown here:
static InetAddress getLocalHost( )
static InetAddress getByName(String hostName)
static InetAddress[ ] getAllByName(String hostName)
The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to resolve the host name, they throw an UnknownHostException.
On the Internet, it is common for a single name to be used to represent several machines. In the world of web servers, this is one way to provide some degree of scaling. The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It will also throw an UnknownHostException if it can't resolve the name to at least one address.
The following example prints the addresses and names of the local machine and two well-known Internet web sites:
// Demonstrate InetAddress.
public static void main(String args) throws
InetAddress Address = InetAddress.getLocalHost();
Address = InetAddress.getByName("starwave.com");
InetAddress SW = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
Here is the output produced by this program. (Of course, the output you see will be slightly different.)
This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".
View Tutorial By: sufficient for new commer at 2008-05-09 00:41:58
View Tutorial By: Tony at 2009-08-13 22:39:48
View Tutorial By: Vaibhav at 2009-12-15 23:37:49
View Tutorial By: Sparx at 2010-01-05 13:51:56
View Tutorial By: vipul at 2010-03-25 00:33:54
View Tutorial By: vamsi at 2010-05-14 23:09:03
View Tutorial By: jawahar at 2010-08-03 00:23:52
View Tutorial By: GSA at 2010-11-23 02:36:26
View Tutorial By: RDMA at 2011-01-04 14:30:15
View Tutorial By: Marcin at 2011-05-17 05:24:51
View Tutorial By: FLORIAN at 2011-09-14 09:04:42
View Tutorial By: arjuna at 2011-11-23 03:31:46
View Tutorial By: Hala at 2013-11-15 22:42:36
Most Viewed Articles (in Java )
Most Emailed Articles (in Java)