Friday, August 28, 2009

Retrieve IP information of my machine

Sometimes you require to retrieve IP information of current machine your are running using Java Program.
Using following program you can get  main Local IP Address,main local host name, alt local ip addresses,alt local host names.

Java provides class java.net.InetAddress which presents an Internet Protocol (IP) address.There are some of useful methods as below which one can deal with to retrieve host name from IP and from IP to host name.

Useful InetAddress methods :
1. getLocalHost() -return local host
2. getByName(String host)  - Determines the IP address of a host, given the host's name
3. getAllByName(String host)- Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system


Please refer to InetAddress J2SE 6.0 Documentation for more information.


Java Program to retrieve IP Information of my machine : 

package com.anuj.network;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class RetrieveMyMachineIPInfo {

    /**
     * Tells you the domain name and IP of the machine you are running.
     *
     * @param args not used.
     */
    public static void main(String[] args) {
        try {
            InetAddress localaddr = InetAddress.getLocalHost();
            System.out.println("main Local IP Address : " + localaddr.getHostAddress());
            System.out.println("main Local hostname   : " + localaddr.getHostName());
            System.out.println();

            InetAddress[] localaddrs = InetAddress.getAllByName("localhost");
            for (int i = 0; i < localaddrs.length; i++) {
                if (!localaddrs[i].equals(localaddr)) {
                    System.out.println("alt  Local IP Address : " + localaddrs[i].getHostAddress());
                    System.out.println("alt  Local hostname   : " + localaddrs[i].getHostName());
                    System.out.println();
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Can't detect localhost : " + e);
        }
    }
}

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment