Home Java Network ReadIPAddress
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

ReadIPAddress

Advertisement
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.

 

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 19, 2008

Ask Questions?    Discuss: ReadIPAddress  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Zaxarias
August 25, 2012
jsFYbQLrbwvskwyiA

CGI.HTTP_X_Forwarded_For does not apply here since any of HTTP_X_FORWARDED_FOR, HTTP_X_FORWARDED or VIA are not present in CGI scope valarbies. Have you tried a with a proxy set in your browser and have seen those values ? I do not see them on cf9, cf8, railo3.2 and with variuos OS (gentoo or freebsd). Any advice ?
DMCA.com