如何在InetAddress.getbyName
的输出中移除斜杠?
更新
感谢大家,我已经解决了。
其中一个解决方案是:
String ip_old = myInetaddress.toString();
String ip_new = ip_old.substring(1);
如何在InetAddress.getbyName
的输出中移除斜杠?
更新
感谢大家,我已经解决了。
其中一个解决方案是:
String ip_old = myInetaddress.toString();
String ip_new = ip_old.substring(1);
如果你只想要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
内在地将这两个字段保持分开。
我假设你在这之后要执行toString操作?为什么不直接使用普通的字符串操作,比如substring呢?
InetAddress
已经在内部分别保留了主机名和地址,你只需要像我的回答那样询问它的地址即可。你能解释一下为什么不想使用逻辑方式吗? - Mark Peters