起初:没有单一的地址。您的机器至少有两个地址(“lo”上的 127.0.0.1 和“eth1”上的 192.168.1.1)。
你想要这个:列出网络接口
正如您所料,您无法自动检测哪个路由器连接到您的任何路由器,因为这需要对路由表进行潜在的复杂解析。但是,如果您只想要任何非本地地址,这应该足够了。可以肯定的是,尝试在 vista 或 Windows 7 上至少使用一次,因为它们添加了 IPv6 地址。
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets
{
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}
以下是示例程序的示例输出:
Display name: bge0
Name: bge0
InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress: /121.153.225.59
Display name: lo0
Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1
InetAddress: /127.0.0.1