Fay Zan Fay Zan - 1 year ago 128
Java Question

Extracting the hostname/ip address from an URL in Android

Let's say I saved a URL of I just want to extract can do this by using this method


But what if the saved URL is ?How do I automatically extract just the IP address?Because the method I just used would display

I am using Java on Android Studio

I used

str = url.toString();
ip = str.substring(str.indexOf('/')+1, str.lastIndexOf(':');

because the second one made me crash and I could not find ways to fix it

Answer Source

Edit! : For Android (Java) use the following code :

(new URL(urlToParse)).getHost();

or if you already have an URL object just the getHost() method (for hostname)

getAuthority() - (for hostname:port)

for other parts consult https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

What language are you using ?

How about using String.split(':') or String.lastIndexOf(':') (and indexof '/') if they are available in your language of choice ?

You can also use regex - Regular Expressions but that might be an overkill for such a simple task. But it sure is more accurate/correct.

Also many languages provide URL parsing for you to extract the hostname/ip-address .

naive method :

str = url.toString();
ip = str.substring(str.indexOf('/')+1, str.lastIndexOf(':');

less naive method :

str = url.toString();
ip = str.split('/')[2].split(':')[0];

regex (only for ip-address based urls) :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download