InetAddress Example program in Java

By: Grenfel Emailed: 1599 times Printed: 2051 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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( )
throws UnknownHostException
static InetAddress getByName(String hostName)
throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException

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.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("starwave.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}

Here is the output produced by this program. (Of course, the output you see will be slightly different.)

default/206.148.209.138
starwave.com/204.202.129.90
www.nba.com/204.202.130.223

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(13)


1. View Comment

more info needs to be given ............

View Tutorial          By: sufficient for new commer at 2008-05-09 00:41:58
2. View Comment

excellent for a beginer in inet address ...

View Tutorial          By: Tony at 2009-08-13 22:39:48
3. View Comment

Can you give me an example to create InetAddress from IP address like 206.148.209.138

View Tutorial          By: Vaibhav at 2009-12-15 23:37:49
4. View Comment

Would be great if you also showed how to manipulate the output too.

View Tutorial          By: Sparx at 2010-01-05 13:51:56
5. View Comment

good but very simple program.........

View Tutorial          By: vipul at 2010-03-25 00:33:54
6. View Comment

it shows error
java.lang.NoClassDefFoundError: inetaddresstest/InetAddressTest
Caused by: java.lang.ClassNotFoundException: inetaddresstest.InetAddressTest
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: inetaddresstest.InetAddressTest. Program will exit.
Exception in thread "main"
Java Result: 1


View Tutorial          By: vamsi at 2010-05-14 23:09:03
7. View Comment

excellent notes

View Tutorial          By: jawahar at 2010-08-03 00:23:52
8. View Comment

I am getting

jayana-desktop/127.0.0.1
Exception in thread "main" java.net.UnknownHostException: starwave.com: starwave.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1145)
at java.net.InetAddress.getAllByName(InetAddress.java:1072)
at java.net.InetAddress.getAllByName(InetAddress.java:1008)
at java.net.InetAddress.getByName(InetAddress.java:958)
at Test.main(Test.java:9)
what might be the reason?


View Tutorial          By: GSA at 2010-11-23 02:36:26
9. View Comment

@Vaibhavn if you use an IP instead of a host name it works too!

View Tutorial          By: RDMA at 2011-01-04 14:30:15
10. View Comment

Does anybody know how to force using IPv6 by my laptop??
I connect my computer to another one locally, disable IPv4 stack on my NIC, assign static IPv6 address (which is displayed and confirmed by ipconfig command in cmd) and after all what I get from these two lines of code?

InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);

Marcin-Komputer/127.0.0.1

:((((
What is wrong?what I need to change to work with my IPv6 address??please, give me some advice..


View Tutorial          By: Marcin at 2011-05-17 05:24:51
11. View Comment

HI all i would like to send the result of " InetAddress Address = InetAddress.getLocalHost(); " to a Jtextfield , so that I can display it in a gui like so:

/---------------------------------------------------------------\
| TITLE: My super gui that looks very nice! - [] X |
|---------------------------------------------------------------|
| |-------------------------------------------| |
| | My Ip address in a JTextField | <-JTxtField|
| |-------------------------------------------| |
| |
| |
\---------------------------------------- ----------------------/

I'm pretty new to java so please don't be to technical. ;-)

Thanks in advance


View Tutorial          By: FLORIAN at 2011-09-14 09:04:42
12. View Comment

how can get ip url...?

View Tutorial          By: arjuna at 2011-11-23 03:31:46
13. View Comment

How to display the ARP Mapping Table of a given host ?

View Tutorial          By: Hala at 2013-11-15 22:42:36

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Grenfel
Verifying a Signed JAR File example
Bitwise and Bit Shift Operators example in Java
JavaBeans Basic Concepts
The Differences Between Simple and Classic Tags in JSP
Bitwise Logical Operators in C
DispatchAction in Struts
union example program in C
Comparison operators in JSP
Basics of Structures in C
register Variables in C
Struts and Tiles - Steps to use Struts and Tiles
The if else statement in C
Character Counting sample program in C
Installing JSF
cin.ignore() in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
InetAddress Example program in Java
Recursion in java
Method Overriding in Java
Abstract classes in Java
XML and Java - Parsing XML using Java Tutorial
Vector example in Java
Using StringTokenizer in Java
How to use ArrayList in Java
How to use Iterator in Java
FileReader and FileWriter example program in Java
Read from a COM port using Java program
Method Overloading (function overloading) in Java
compareTo( ) in Java
wait(), notify() and notifyAll() in Java - A tutorial
Most Emailed Articles (in Java)
inheritance in Java
Creating Users and Passwords with Tomcat using tomcat-users.xml
interface Example in Java
Java program to display numbers from 1 to 10 on Applet
How to modify the objects using java classes
Using Parameters in JasperReports
What is a Java CLASSPATH and why you need it?
Java scripting embedded in HTML.
Executing Java Scripts
Recursion in java
The Basic Structure of a Simple Java program
Reverse a number in Java
Vector in Java - Sample Program
Java program to print prime numbers using Thread
Draw a bar chart in Java