【问题标题】:How to fetch both IPv4 and IPv6 on dual stack OS如何在双栈操作系统上同时获取 IPv4 和 IPv6
【发布时间】:2015-06-12 08:42:51
【问题描述】:

我有双栈机器。

我的问题是我只能使用 IPv4

InetAddress address = InetAddress.getLocalHost();

如果我使用网络接口 API,那么我将获得所有 IP 地址,其中包括我的 MAC 地址以及 IP 地址的形式。 why-do-i-get-multiple-global-ipv6-addresses-listed-in-ifconfig

现在有什么方法可以让我的机器同时获得 IPv4 和 IPv6。

【问题讨论】:

    标签: java network-programming


    【解决方案1】:

    在 Linux 中, InetAddress.getLocalHost() 将查找主机名,然后返回 DNS 分配给该主机名的第一个 IP 地址。如果您在文件 /etc/hosts 中有该主机名,它将获取该文件中该主机名的第一个 IP 地址。

    如果你注意这个方法只返回一个 InetAddress。

    如果您没有指定主机名,很可能是 localhost.localdomain。您可以使用命令行设置主机名:

    hostname [name]
    

    或通过在文件 /etc/sysconfig/network 中设置它

    如果您想获取分配给主机名的所有 IP 地址,包括 IPv6,您可以使用:

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

    如果要获取分配给主机网络接口的所有 IP 地址,包括 IPv6,则必须使用类 NetworkInterface。

    我在这里粘贴一些示例代码:

    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();
            }
        }
    }
    

    对于这个例子,我从InetAddress.getLocalHost().getHostAddress() is returning 127.0.1.1 中的一个响应中获得了代码

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 2020-01-12
      • 1970-01-01
      • 2011-01-17
      • 2012-05-09
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多