使用URL字符串获取IP地址? (JAVA)

时间:2012-02-15 01:49:14

标签: java ip ip-address inetaddress

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

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

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

InetAddress address = InetAddress.getByName(urlStr);

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

2 个答案:

答案 0 :(得分:61)

试试这个:

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

获取原始IP:

String ip = address.getHostAddress();

答案 1 :(得分:10)

您需要将hostname提供给getByName()方法并返回

  

主机的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());