Emm Jay
Emm Jay

Reputation: 380

Android : Need help in getting IP Address from hostname

I'm using the following tool in my activity and its working. But the output (hostname) that i get is not the way i want. For example, if i need to find the IP of google, i get it like www.google.com/74.125.224.72

it should be just like 74.125.224.72

I'm new to Android, please help me out. Here's my code :

String host = editText1.getText().toString();
try {
    InetAddress[] hostInetAddress = InetAddress.getAllByName(host);
    String all = "";
    for(int i = 0; i < hostInetAddress.length; i++){
        all = all + hostInetAddress[i].toString() + "\n";
    }
    textInetAddress.setText(all);
}

Upvotes: 0

Views: 162

Answers (3)

Don Chakkappan
Don Chakkappan

Reputation: 7560

No need of for loop. This will work.

hostInetAddress[0].getHostAddress();

Upvotes: 0

Vamshi
Vamshi

Reputation: 1495

Try this:

String[] ip = all.split("/");
textInetAddress.setText(ip[1]);

Upvotes: 0

Jigar
Jigar

Reputation: 791

get your name/ip_address by using:

InetAddress address = InetAddress.getByName(new URL(urlString).getHost());
//it will fetch name/ip_address (eg. www.google.com/74.125.224.72) of the url you enter

and then get only ip_address using:

String ip = address.getHostAddress();
//it will fetch only ip_address (eg. "74.125.224.72" ) from the abouve url

so instead of

 for(int i = 0; i < hostInetAddress.length; i++){
                    all = all + hostInetAddress[i].toString() + "\n";
                }

use the following code

 for(int i = 0; i < hostInetAddress.length; i++){
                    all = all + hostInetAddress[i].getHostAddress().toString() + "\n";
                }

Upvotes: 1

Related Questions