Get the local IP address using Java.

There are many ways to get the local IP address using Java. And we are going to examine various methods. On the face of it, InetAddress.getLocalHost() should give you the IP address of this host. But it doesn't. One of the major problems are that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable outside of your machine or your LAN. For example, they could be IP addresses for virtual network devices, private network IP addresses, and so on.

Following method use opendns.com to get the local IP address.

package learnjava.System;

/** * Created by Isuru on 11/04/2017. */import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

// class with main() methodpublic class IPAddress
{

    public static void main(String[] args)
    {
        String ipAdressDns  = "";
        try {
            String command = "nslookup myip.opendns.com resolver1.opendns.com";
            Process proc = Runtime.getRuntime().exec(command);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String s;
            while ((s = stdInput.readLine()) != null) {
                ipAdressDns  += s + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(ipAdressDns);
    }

}


Following method, works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8 is not needed to be reachable.

package learnjava.System;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/** * Created by Isuru on 11/04/2017. */public class GetIPAddressUsingDatagramSocket {

    public static void main(String args[]){
        try(final DatagramSocket socket = new DatagramSocket()){
            socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
            String ip = socket.getLocalAddress().getHostAddress();
            System.out.print(ip);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }

}


Following class prints out all the IP addresses assigned to the Internet Interfaces.

package learnjava.System;

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/** * Created by Isuru on 11/04/2017. */public class LocalAddress {

    public static void main(String args[]){
        try {
            Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
            while( b.hasMoreElements()){
                for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
                    if ( f.getAddress().isSiteLocalAddress())
                        System.out.println(f.getAddress());
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

}


There may be other methods to get the local IP address. Please comment any other method you found useful.


Comments

Popular posts from this blog

Offers on Friday, April 24, 2020

Fatal: LoadModule: error loading module 'mod_sql_mysql.c'