How do I get IP address of localhost?

Category: java.net, viewed: 10185 time(s).
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddressExample
{
    public static void main(String[] args)
    {
        try
        {
            InetAddress address = InetAddress.getLocalHost();

            byte[] ip = address.getAddress();

            int i = 4;
            String ipAddress = "";			
            for (byte b : ip)
            {
                ipAddress += (b & 0xFF);
                if (--i > 0)
                {
                    ipAddress += ".";
                }
            }

            System.out.println(ipAddress);
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
    }
}


Java Training

Sponsored Links