[英]How to get the IP address for remote host using 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。 這可能嗎 ? 是否可以在不首先創建套接字的情況下獲取 IP?
嘗試這個:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
byte[] raw = inetAddress.getAddress();
字節數組現在包含 IP 地址字節。
使用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.