[英]How to get the IP address for remote host using Java
I need to get the IP address for remote hosts.我需要获取远程主机的 IP 地址。 I tried the following and works fine:
我尝试了以下方法并且工作正常:
socket = factory.createSocket(hostName, port);
InetAddress remoteIP = socket.getInetAddress();
String[] remoteIPOnly = remoteIP.toString().split("\\/");
System.out.println("Remote IP is: "+remoteIPOnly[1]);
But, I need a way where I don't have to specify a port number.但是,我需要一种不必指定端口号的方法。 Ie, I need the IP for a remote host despite the port number.
即,尽管有端口号,但我仍需要远程主机的 IP。 Is this possible ?
这可能吗 ? Is it possible to get the IP without creating socket from the first place ?
是否可以在不首先创建套接字的情况下获取 IP?
Try this:尝试这个:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
byte[] raw = inetAddress.getAddress();
The byte array now contains the IP addresses bytes.字节数组现在包含 IP 地址字节。
Use getHostAddress()
as below:使用
getHostAddress()
如下:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
String ipAddress = inetAddress.getHostAddress();
System.out.println(ipAddress );//prints 66.152.109.61
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.