Get IP address with URL string? (Java)
Asked Answered
B

2

46

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?

Bevatron answered 15/2, 2012 at 1:49 Comment(0)
H
73

Try this:

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

To get the raw IP:

String ip = address.getHostAddress();
Heisel answered 15/2, 2012 at 2:3 Comment(3)
Thanks that worked, though it returns a name/ip address. If I want to use the IP address for a socket do I need to use the '/' as a delimiter to only extract the ip address or would it work as is?Bevatron
just call address.getHostAddress() on the InetAddess object to get a string version of the IP. Or better, create the socket directly with the InetAddress object.Popsicle
@brettw: I edited my answer at the same time that you commented.Heisel
L
10

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());
Lorrettalorri answered 15/2, 2012 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.