2012-11-19 112 views
1

我需要獲取遠程主機的IP地址。我嘗試以下,並正常工作:如何使用Java獲取遠程主機的IP地址

socket = factory.createSocket(hostName, port); 
InetAddress remoteIP = socket.getInetAddress(); 
String[] remoteIPOnly = remoteIP.toString().split("\\/"); 
System.out.println("Remote IP is: "+remoteIPOnly[1]); 

但是,我需要的方式,我不必指定一個端口號。即,儘管有端口號,我仍需要遠程主機的IP。這可能嗎 ?是否有可能從第一個地方創建套接字?

回答

0

使用getHostAddress()

InetAddress inetAddress = InetAddress.getByName("www.google.com"); 
    String ipAddress = inetAddress.getHostAddress(); 
    System.out.println(ipAddress);//prints 66.152.109.61 
2

試試這個:

InetAddress inetAddress = InetAddress.getByName("www.google.com"); 
byte[] raw = inetAddress.getAddress(); 

的字節數組現在包含IP地址字節。如下

+0

確實工作。我正要發佈相同的答案:) – Burkhard

相關問題