获取带有 URL 字符串的 IP 地址?(爪哇)

2022-09-01 00:30:30

在我的程序中,用户输入一个 url 字符串,比如

http://www.engineering.uiowa.edu/~hawkeng//fall01/graphics/potato.gif

我如何获得此网址的IP地址?我尝试使用

InetAddress address = InetAddress.getByName(urlStr);

但结果始终返回 null。获取 IP 地址的正确方法是什么?


答案 1

试试这个:

InetAddress address = InetAddress.getByName(new URL(urlString).getHost());

要获取原始 IP,请执行以下操作:

String ip = address.getHostAddress();

答案 2

你需要给getByName()方法,它返回hostname

给定主机名称的主机的 IP 地址。

URL url = new URL("http://www.engineering.uiowa.edu/~hawkeng//fall01/graphics/potato.gif");
System.out.println(url.getHost());
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.toString());

输出 =www.engineering.uiowa.edu/128.255.17.182

要获取IP address

String temp = address.toString();
String IP = temp.substring(temp.indexOf("/")+1,temp.length());