Get IP address with URL string? (Java)

2019-01-11 12:33发布

In my program a user enters a url string, say

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

how would I get the IP address of this url? I tried using

InetAddress address = InetAddress.getByName(urlStr);

but the result always comes back null. What is the proper way to get the IP address?

2条回答
倾城 Initia
2楼-- · 2019-01-11 12:47

You need to give hostname to getByName() method and it returns

the IP address of a host, given the host's name.

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());

Output = www.engineering.uiowa.edu/128.255.17.182

To get the IP address

String temp = address.toString();
String IP = temp.substring(temp.indexOf("/")+1,temp.length());
查看更多
Melony?
3楼-- · 2019-01-11 13:03

Try this:

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

To get the raw IP:

String ip = address.getHostAddress();
查看更多
登录 后发表回答