问题描述
我有双栈机。
我的问题是我只使用
InetAddress address = InetAddress.getLocalHost();
如果我使用网络接口API,那么我将获得包含我的MAC地址的所有IP地址以IP地址的形式。
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
现在有什么方法可以同时获得我的机器的IPv4和IPv6。
Now is there any way i can get both IPv4 and IPv6 of my machine.
推荐答案
在Linux中,
InetAddress.getLocalHost()将查找主机名,然后返回分配的第一个IP地址通过DNS到该主机名。如果文件/ etc / hosts中有该主机名,它将获得该文件中该主机名的第一个IP地址。
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.
如果你注意这个方法只返回一个InetAddress。
If you pay attention this method returns only one InetAddress.
如果您尚未分配主机名,则很可能是localhost.localdomain。您可以使用命令行设置主机名:
If you haven't assigned a hostname, most probably it will be localhost.localdomain. You can set the hostname with command line:
hostname [name]
或将其设置在文件/ etc / sysconfig / network中
or by setting it in file /etc/sysconfig/network
如果你想得到所有ip分配给您可以使用的主机名的地址(包括IPv6):
If you want to get all ip addresses, including IPv6, assigned to a hostname you can use:
InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
如果要获取分配给主机网络接口的所有IP地址(包括IPv6),则必须使用类NetworkInterface。
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
这篇关于如何在双栈操作系统上同时获取IPv4和IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!