我正在編寫一個客戶端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