【发布时间】:2013-09-02 02:44:43
【问题描述】:
我正在编写一个客户端 Java 程序,它需要知道用于(通过 tcp)连接到远程服务器的本地 IP 地址。
问题是调用 Socket.getLocalAddress().getHostAddress() 错误返回(仅在少数情况下)127.0.0.1,而在大多数情况下/PC 中它工作正常...
这里是所用代码的sn-p:
public static String getLocalIPAddress(String serverIP, int port) throws UnknownHostException
{
System.out.println("Executing getLocalIPAddress on "+serverIP + ":" + port);
InetAddress inetAddress = InetAddress.getLocalHost();
String ipAddress = inetAddress.getHostAddress();
try {
Socket s = new Socket(serverIP, port);
ipAddress = s.getLocalAddress().getHostAddress();
System.out.println("Local IP : "+s.getLocalAddress().getHostAddress());
s.close();
} catch (Exception ex) {}
return ipAddress;
}
我在后续案例中获得的输出是
Executing getLocalIPAddress...
Executing getLocalIPAddress on 1.2.3.4:80
Local IP : 6.7.8.9
我在失败情况下获得的输出是
Executing getLocalIPAddress...
Executing getLocalIPAddress on 1.2.3.4:80
Local IP : 127.0.0.1
请注意,在失败的情况下,它并没有经历异常。
非常感谢任何建议。
【问题讨论】:
-
你的意思是Local IP:...后面应该跟去link一样的东西吗?
-
远程地址是否远程?还是 127.0.0.1?我建议您将远程地址与本地地址一起打印出来。如果它们都是 127.0.0.1 则没有问题要解决。
-
是的本地地址是 6.7.8.9 而远程地址是 1.2.3.4