2012-11-19 106 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

相关问题