java InetAddress.toString() 返回一个正斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12947435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
InetAddress.toString() returns a forward slash
提问by Mike G
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:
我有一个类型为 的可变数据包DatagramPacket
。虽然packet.getAddress().toString()
结果是一个代表 IP 地址的字符串,但它有一个额外的/
附加到字符串的开头:
/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.
我可以轻松删除前导'/'
,但是有没有更好的方法来获取 IP 的字符串表示?我很担心,因为如果'/'
在其他情况下还有更多怎么办。
Thanks!
谢谢!
回答by Paul Bellora
Use the following:
使用以下内容:
packet.getAddress().getHostAddress()
From the documentation:
从文档:
Returns the IP address string in textual presentation.
以文本形式返回 IP 地址字符串。
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.
将此 IP 地址转换为
String
. 返回的字符串格式为:主机名/文字 IP 地址。如果主机名未解析,则不执行反向名称服务查找。主机名部分将由空字符串表示。
回答by Aniket Inge
If you just want the IP, use the host address:
如果您只需要 IP,请使用主机地址:
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
您看到的斜线可能是当您尝试打印返回的 InetAddress 时对返回的 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];
But there is no reason at all to go to a String intermediary here. InetAddress keeps the two fields separate intrinsically.
但是完全没有理由去这里的 String 中介。InetAddress 使这两个字段本质上分开。