我希望从我的Java小程序中确定本地IP地址。问题在于当同一台机器有局域网和互联网连接(例如palm,VMWare等)时,会有多个IP地址。
以下是我的测试:
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();
}
}
结果是:
HostName = xxxx
HostAddressLocal = xx.xx.xx.xx
hostAddress = 10.10.11.51
hostAddress = 192.168.23.1
hostAddress = 192.168.106.1
xx.xx.xx.xx不是正确的地址,正确的是10.10.11.51。
针对jarnbjo的回复进行编辑:
你的预测准确。你理解了我的问题。客户端可以通过代理连接,因此我不能使用你提供的第一种方法。如果我在我的电脑上执行以下代码:
Socket s = new Socket("www.w3c.org", 80);
InetAddress ip = s.getLocalAddress();
System.out.println("Internet IP = " + ip.toString());
s.close();
我有这个结果:
Internet IP = /127.0.0.1
而不是10.10.11.51