Thursday, 20 September 2012

How to get Local IP Address in Java?

Used following function to fetch IP Address

public String getIPAddress()
{
        String IPAddress="";
        try
        {
            IPAddress = InetAddress.getLocalHost().getHostAddress();
        }
        catch (UnknownHostException errorException)
        {
            logErrorInfo("getIPAddress() function: " + errorException);
        }
        return IPAddress;
}
   

Present in Package: java.net.InetAddress

> InetAddress class represents IP Address
> getLocalHost() is static method which returns Host and this throws UnknownHostException which is handled in try catch block
> getHostAddress returns String IP address 

No comments:

Post a Comment