0

I guess my question is pretty simple to answer for the guys out here? The thing is that when i did the following code:

InetAddress addr;
addr=InetAddress.getByName("192.168.1.1");
Toast.makeText(this,"InetAddress Value: "+addr.toString(),Toast.LENGTH_LONG).show();

addr value return was /192.168.1.1 I want to know what is the thing I am doing wrong? Thanks in advance!!!

codeMagic
  • 44,549
  • 13
  • 77
  • 93

1 Answers1

2

Answer from here.

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.

Community
  • 1
  • 1
chinna_82
  • 6,353
  • 17
  • 79
  • 134
  • even when i just code Toast.makeText(this,"InetAddress Value: "+addr,Toast.LENGTH_LONG).show(); it gives same answer. – Prajwal Shakya Sep 18 '13 at 02:40
  • what you want to see..? – chinna_82 Sep 18 '13 at 03:50
  • public void getInet(View v1) throws UnknownHostException{ String asd=ed1.getText().toString(); InetAddress addr=InetAddress.getByName(asd); Toast.makeText(this, "Inet Address: "+addr, Toast.LENGTH_LONG).show(); } The above simple code gives any ipaddress passed in edittext as /+edittext value. is there anyway to remove front slash – Prajwal Shakya Sep 18 '13 at 04:05
  • What you want to see in Toast.. what your expected output? – chinna_82 Sep 18 '13 at 04:06
  • it shud be only 192.168.1.1 as i just want to convert string to inetaddress so that the ip can be pinged – Prajwal Shakya Sep 18 '13 at 04:07
  • check my answer or click on the link i provided to understand on the slash part. Meanwhile you also can use `split("/")` – chinna_82 Sep 18 '13 at 04:13
  • split function is only available to String. The problem is with InetAddress value, I guess, not with the String. if you toast string value it will show 192.168.1.1 but if u toast inetaddress value, it shows /192.168.1.1. Why don't you try one with emulator for my above mentioned code.. You above answer will work only if string returns /192.168.1.1 if i am not wrong – Prajwal Shakya Sep 18 '13 at 04:18