我正在编写一个客户端Java程序,它需要知道用于连接(通过tcp)到远程服务器的本地IP地址。getLocalAddress在连接套接字上返回127.0.0.1
的问题是,呼叫Socket.getLocalAddress()。getHostAddress()返回错误(只在少数情况下)127.0.0.1,而在大多数情况下/电脑的正常工作......
下面是代码的使用的片段:
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
请注意,在失败的情况下,它没有经历例外。
任何意见是非常感激。
你的意思是本地IP地址:...应该跟随同样的事情,就像你去[link](http://www.whatismyip.com)一样? – lukey
远程地址是否为远程地址?或者它是127.0.0.1?我建议你打印出远程地址和本地地址。如果它们都是127.0.0.1,这里没有问题要解决。 – EJP
是本地地址是6.7.8.9,而远程地址是1.2.3.4 – MDot