Get IP address with URL string? (Java)



In my program a user enters a url string, say

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?


Posted 2012-02-15T01:49:14.477

Reputation: 341



Try this:

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

To get the raw IP:

String ip = address.getHostAddress();

Victor Stafusa

Posted 2012-02-15T01:49:14.477

Reputation: 7 155

1Thanks 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? – user1205853 – 2012-02-15T02:11:08.867

2just 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. – brettw – 2012-02-15T02:24:33.963

@brettw: I edited my answer at the same time that you commented. – Victor Stafusa – 2012-02-15T02:26:26.010


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("");
InetAddress address = InetAddress.getByName(url.getHost());

Output =

To get the IP address

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


Posted 2012-02-15T01:49:14.477

Reputation: 27 422