Tuesday, September 25, 2012

IP address of localhost from Java Program:

Java networking API provides method to find IP address of localhost from Java program by using java.net. InetAddress class. It’s rare when you need IP address for localhost in Java program. Mostly I used Unix command to find IP address of localhost. For all practical purpose where program doesn’t need IP address but you need to troubleshoot any networking issues, Use DOS or windows command or Use Linux commands. Recently one of my friend faced this question in a core Java interview, where they are expecting Java developer with some socket programming experience, But until you know or you have done it before its hard to answer this fact based question, which motivates me to write this post. In this Java tutorial we will see How to find IP address of localhost from Java program. By the way it’s also good to remember list of Unix networking commands to troubleshoot any networking issues related to Java application in Unix environment.

IP Address of localhost from Java program

How to find IP address of localhost in Java program
As I said InetAddress from java.net package is used to represent an IP address in Java. an IP address is a 32 or 128 bit unsigned number used by IP protocol which is backbone of many popular protocols like TCP and UDP. There are two kinds of IP address IPv4 and IPv6 and IP address is associated with host which can be find by host name resolution process. Hostname resolution is performed by combining local machine configuration and network naming services such as the  DNS(Domain name system) and NIS(Network Information Service). InetAddress has method to resolve hostname and IP address and vice versa. Here is a complete code example of finding IP address from Java program.


import java.net.UnknownHostException;

/**
 * Simple Java program to find IP Address of localhost. This program uses

 * InetAddress from java.net package to find IP address.
 *
 * @author Javin Paul
 */
public class IPTest {
 
 
    public static void main(String args[]) throws UnknownHostException {
   
        InetAddress addr = InetAddress.getLocalHost();
     
        //Getting IPAddress of localhost - getHostAddress return IP Address

        // in textual format
        String ipAddress = addr.getHostAddress();
     
        System.out.println("IP address of localhost from Java Program: " + ipAddress);
     
        //Hostname
        String hostname = addr.getHostName();
        System.out.println("Name of hostname : " + hostname);
     
    }
 
}

Output:
IP address of localhost from Java Program: 190.12.209.123
Name of hostname : PCLOND3433


That’s all on How to find IP address of localhost from Java. Its nice tip to know but as I said java.net is not a common package like java.lang or java.util. Best way to learn and remember networking concepts in Java is to write some client server program which uses these essential classes.



No comments:

Post a Comment