在 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 中的一个响应中获得了代码