Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address with URL string? (Java)

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?

like image 437
user1205853 Avatar asked Feb 15 '12 01:02

user1205853


People also ask

How do you check if a string is an IP address in Java?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.

How do I get client IP from request?

In Java, you can use HttpServletRequest. getRemoteAddr() to get the client's IP address that's accessing your Java web application.


1 Answers

Try this:

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

To get the raw IP:

String ip = address.getHostAddress(); 
like image 68
Victor Stafusa Avatar answered Nov 06 '22 11:11

Victor Stafusa