Getting the IP address of the current machine using Java

Posted in :

On a computer that has one network adapter, the IP address that is chosen is the Primary IP address of the network adaptor in the computer. However, on a multiple-homed computer, the stack must first make a choice. The stack cannot make an intelligent choice until it knows the target IP address for the connection.

When the program sends a connect() call to a target IP address, or sends a send() call to a UDP datagram, the stack references the target IP address, and then examines the IP route table so that it can choose the best network adapter over which to send the packet. After this network adapter has been chosen, the stack reads the Primary IP address associated with that network adapter and uses that IP address as the source IP address for the outbound packets.

Document

If you want to activate second IP and its for example LAN, unplug it and after 10 sec plug in back. Other IP might be selected as host IP in routing table.

You can get 2nd IP from getNetworkInterfaces.

Try to run followed code:

public static void main(String[] args) throws Exception
{
    System.out.println("Your Host addr: " + InetAddress.getLocalHost().getHostAddress());  // often returns "127.0.0.1"
    Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
    for (; n.hasMoreElements();)
    {
        NetworkInterface e = n.nextElement();

        Enumeration<InetAddress> a = e.getInetAddresses();
        for (; a.hasMoreElements();)
        {
            InetAddress addr = a.nextElement();
            System.out.println("  " + addr.getHostAddress());
        }
    }
} 

 

This could be a bit tricky in the most general case.

On the face of it, InetAddress.getLocalHost() should give you the IP address of this host. The problem is 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.

What this means is that the IP address returned by InetAddress.getLocalHost() might not be the right one to use.

How can you deal with this?

  • One approach is to use NetworkInterface.getNetworkInterfaces() to get all of the known network interfaces on the host, and then iterate over each NI’s addresses.
  • Another approach is to (somehow) get the externally advertized FQDN for the host, and use InetAddress.getByName() to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?)
  • A variation of the previous is to get the preferred FQDN from a config file or a command line parameter.
  • Another variation is to get the preferred IP address from a config file or a command line parameter.

In summary, InetAddress.getLocalHost() will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with “complicated” networking.


I am able to get all the IP addresses associated all Network Interfaces, but how do i distinguish them?

  • Any address in the range 127.xxx.xxx.xxx is a “loopback” address. It is only visible to “this” host.
  • Any address in the range 192.168.xxx.xxx is a private (aka site local) IP address. These are reserved for use within an organization. The same applies to 10.xxx.xxx.xxx addresses, and 172.16.xxx.xxx through 172.31.xxx.xxx.
  • Addresses in the range 169.254.xxx.xxx are link local IP addresses. These are reserved for use on a single network segment.
  • Addresses in the range 224.xxx.xxx.xxx through 239.xxx.xxx.xxx are multicast addresses.
  • The address 255.255.255.255 is the broadcast address.
  • Anything else should be a valid public point-to-point IPv4 address.

In fact, the InetAddress API provides methods for testing for loopback, link local, site local, multicast and broadcast addresses. You can use these to sort out which of the IP addresses you get back is most appropriate.

 

from:

https://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java


sample 2:

public String getLocalIpAddress() 
{
	try 
	{
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
		{
			NetworkInterface intf = en.nextElement();
			for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
			{
				InetAddress inetAddress = enumIpAddr.nextElement();
				if (!inetAddress.isLoopbackAddress()) 
				{
					return inetAddress.getHostAddress().toString();
				}
			}
		}
	} 
	catch (SocketException ex) 
	{
		Log.e("SRM", ex.toString());
	}
	return null;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *