0

I have dual stack machine .

My problem is i am getting only IPv4 using

InetAddress address = InetAddress.getLocalHost();

and If i use Network Interface API then i get all the IP address in which includes my MAC addrres as well in the form of IP address. why-do-i-get-multiple-global-ipv6-addresses-listed-in-ifconfig

Now is there any way i can get both IPv4 and IPv6 of my machine.

Community
  • 1
  • 1
T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

0

In Linux, InetAddress.getLocalHost() will look for the hostname and then return the first IP address assigned to that hostname by DNS. If you have that hostname in the file /etc/hosts, it will get the first IP address in that file for that hostname.

If you pay attention this method returns only one InetAddress.

If you haven't assigned a hostname, most probably it will be localhost.localdomain. You can set the hostname with command line:

hostname [name]

or by setting it in file /etc/sysconfig/network

If you want to get all ip addresses, including IPv6, assigned to a hostname you can use:

InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());

If you want to get all ip addresses, including IPv6, assigned to a host's network interfaces, you must use class NetworkInterface.

Here I'm pasting some example code:

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketException;
import java.net.NetworkInterface;
import java.util.*;

public class Test
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("getLocalHost: " + InetAddress.getLocalHost().toString());

            System.out.println("All addresses for local host:");
            InetAddress[] addr = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
            for(InetAddress a : addr)
            {
              System.out.println(a.toString());
            }
        }
        catch(UnknownHostException _e)
        {
            _e.printStackTrace();
        }

        try
        {
            Enumeration nicEnum = NetworkInterface.getNetworkInterfaces();
            while(nicEnum.hasMoreElements())
            {
                NetworkInterface ni=(NetworkInterface) nicEnum.nextElement();
                System.out.println("Name: " + ni.getDisplayName());
                System.out.println("Name: " + ni.getName());
                Enumeration addrEnum = ni.getInetAddresses();
                while(addrEnum.hasMoreElements()) 
                {
                    InetAddress ia= (InetAddress) addrEnum.nextElement();
                    System.out.println(ia.getHostAddress());
                }
            }
        }
        catch(SocketException _e)
        {
            _e.printStackTrace();
        }
    }
}

For this example, I got code from one of the responses in InetAddress.getLocalHost().getHostAddress() is returning 127.0.1.1

Community
  • 1
  • 1
rodolk
  • 5,606
  • 3
  • 28
  • 34