Mike G
Mike G

Reputation: 4959

InetAddress.toString() returns a forward slash

I have a variable packet of type DatagramPacket. While packet.getAddress().toString() results in a String representing an the IP address, it has an extra / appended to the beginning of the String:

/127.0.0.1

I can easily remove the leading '/', but is there a better way to just obtain a string representation of the IP? I am worried because what if there are more '/' in other situations.

Thanks!

Upvotes: 30

Views: 16831

Answers (2)

Aniket Inge
Aniket Inge

Reputation: 25725

If you just want the IP, use the host address:

String address = InetAddress.getByName("stackoverflow.com").getHostAddress();

If you just want the host name, use

String hostname = InetAddress.getByName("stackoverflow.com").getHostName();

The slash you're seeing is probably when you do an implicit toString() on the returned InetAddress as you try to print it out, which prints the host name and address delimited by a slash (e.g. stackoverflow.com/64.34.119.12). You could use

String address = InetAddress.getByName("stackoverflow.com").toString().split("/")[1];
String hostname = InetAddress.getByName("stackoverflow.com").toString().split("/")[0];

But there is no reason at all to go to a String intermediary here. InetAddress keeps the two fields separate intrinsically.

Upvotes: 9

Paul Bellora
Paul Bellora

Reputation: 55233

Use the following:

packet.getAddress().getHostAddress()

From the documentation:

Returns the IP address string in textual presentation.

Contrast that with InetAddress.toString():

Converts this IP address to a String. The string returned is of the form: hostname / literal IP address. If the host name is unresolved, no reverse name service lookup is performed. The hostname part will be represented by an empty string.

Upvotes: 43

Related Questions