在InetAddress.getByName(host)之前加上斜杠

17

如何在InetAddress.getbyName的输出中移除斜杠?


更新

感谢大家,我已经解决了。

其中一个解决方案是:

String ip_old = myInetaddress.toString(); 
String ip_new = ip_old.substring(1); 

4
你现在使用的那个解决方案是一种糟糕的hack。请使用getHostAddress()函数来检索你想要的内容。 - Willem Mulder
2个回答

29

如果你只想要IP地址,使用主机地址:

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

如果你只想要主机名,可以使用

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

编辑

你看到的斜杠可能是因为在对返回的InetAddress进行隐式toString()时,尝试将其打印出来,从而打印出以斜杠分隔的主机名和地址(例如stackoverflow.com/64.34.119.12)。你可以使用

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

但是在这里完全没有必要使用String中介。 InetAddress内在地将这两个字段保持分开。


0

我假设你在这之后要执行toString操作?为什么不直接使用普通的字符串操作,比如substring呢?


是的!刚刚完成了。谢谢!代码- String ip_old = myInetaddress.toString(); String ip_new = ip_old.substring(1); - P R
5
@P Ramesh:这真的是一个非常糟糕的解决方案,因为你没有任何理由将其转换为字符串再转回来。InetAddress 已经在内部分别保留了主机名和地址,你只需要像我的回答那样询问它的地址即可。你能解释一下为什么不想使用逻辑方式吗? - Mark Peters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接