Home Java Network ReadIPAddress



ReadIPAddress
Posted on: March 19, 2008 at 12:00 AM
Here, we are going to explore a method to retrieve the IPAddress of the local system in a very simple example. For this, we use getByName() method of InetAddress class to create a object that contains IP address for the given host name.

ReadIPAddress

     

Here, we are going to explore a method to retrieve the IPAddress of the local system in a very simple example. For this, we use getByName() method of InetAddress class to create a object that contains IP address for the given host name. Using this object we can get IP address using method getHostAddress(). Now we can use the print statement to print this value. If the user enters the host name by keyboard then IP address of local machine will be displayed on console.

getHostAddress(): This method of InetAddress class returns an IPAddress of local system.

 

Here is the code of this program:

import java.net.*;
import java.io.*;

public class ReadIPAddress{
  public static void main(String[] args )throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the host name: ");
    String hostname = input.readLine();
    try {
      InetAddress inetadd = InetAddress.getByName(hostname);
      System.out.println("IP address is: " + inetadd.getHostAddress());
    }
    catch(UnknownHostException e ){
      System.out.println("Could not find IP address for: " + hostname);
    }
  }
} 


Here is the Output of this program:

C:\rose>java ReadIPAddress
Enter the host name: roseindi
IP address is: 192.168.10.104

C:\rose>

 

Download of this program.

 

Related Tags for ReadIPAddress:
cmacclassconsolekeyboardobjectmethoduserprintgetsystemdisplayipkeyvaluestatenameusingoleintthisaddressaisimplecreatelocalifforieexampleaddstatementtohostcontainsexameilcanmachinesplusetrieimenterinnocalasstamntplaytrnetoscaddnetosjispadclesretrieveemlocmeobjpadboardsysxaxampsspsoessatkishallivmplgoeaarstatconssimxpvassrirdthstchialuhatdispboalorejepleplpronolo


More Tutorials from this section

Ask Questions?    Discuss: ReadIPAddress  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.