我想从我的java applet中确定本地IP地址.问题是当同一台机器上有多个IP地址时,它们有LAN和互联网连接(掌上电脑,VMWare ......).
这是我的测试:
public static void main(String[] args) {
try {
String hostName = InetAddress.getLocalHost().getHostName();
System.out.println("HostName = " + hostName);
System.out.println("HostAddressLocal = " +
InetAddress.getLocalHost().getHostAddress());
InetAddress[] inetAddresses = InetAddress.getAllByName(hostName);
for (InetAddress inetAddress : inetAddresses) {
System.out.println("hostAddress = " + inetAddress.getHostAddress());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
HostName = xxxx
HostAddressLocal = xx.xx.xx.xx
hostAddress = 10.10.11.51
hostAddress = 192.168.23.1
hostAddress = 192.168.106.1
Run Code Online (Sandbox Code Playgroud)
其中xx.xx.xx.xx不是正确的地址.正确的是10.10.11.51.
编辑以回应jarnbjo:
你的水晶球说实话.你了解我的问题.客户端可以通过代理连接,因此我无法使用您的第一点.如果我在我的电脑上执行以下代码:
Socket s = new Socket("www.w3c.org", 80);
InetAddress ip = …Run Code Online (Sandbox Code Playgroud)