17

How do I remove the slash in the output of InetAddress.getbyName?


UPDATE

Thanks everyone, I just did it.

One of the solutions is:

String ip_old = myInetaddress.toString(); 
String ip_new = ip_old.substring(1); 
informatik01
  • 16,038
  • 10
  • 74
  • 104
P R
  • 1,293
  • 7
  • 28
  • 58

2 Answers2

29

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();

Edit

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.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
0

I'm assuming you are doing a toString after this? Why don't you just use normal String manipulation, meaning substring?

Chris Aldrich
  • 1,904
  • 1
  • 22
  • 37
  • yes! just did it. Thanks! code- String ip_old=myInetaddress.toString(); String ip_new=ip_old.substring(1); – P R Sep 09 '11 at 12:57
  • 5
    @P Ramesh: That's a really terrible solution since you're going to a String and back for absolutely no reason. The `InetAddress` already keeps the host name and address separately internally, you just have to ask it for the address like in my answer. Can you explain why you don't want to use the logical way? – Mark Peters Sep 09 '11 at 16:56