如何使用Java获取远程主机的IP地址

时间:2012-11-19 06:37:56

标签: java sockets network-programming

我需要获取远程主机的IP地址。我尝试了以下工作并且工作正常:

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

但是,我需要一种不需要指定端口号的方法。即,尽管有端口号,但我需要远程主机的IP。这可能吗 ?是否可以在不创建套接字的情况下获取IP?

2 个答案:

答案 0 :(得分:2)

试试这个:

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

字节数组现在包含IP地址字节。

答案 1 :(得分:0)

使用getHostAddress(),如下所示:

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