Java 中 IP 地址到主机名?
我的主机文件(C:\WINDOWS\system32\drivers\etc\hosts)有一堆 IP 地址到主机名的映射:
# Switches
192.168.200.254 sw-con-ctrl
192.168.201.253 sw-con-ctrl-2
192.168.201.254 sw-con-ctrl-1
# 192.168.188.1 sw-con-ctrl-ylw-1
# 192.168.189.1 sw-con-ctrl-blu
192.168.190.62 access-console
# Routers
192.168.21.1 rtr1
192.168.22.1 rtr2
我试图找到一种通过 Java API 以编程方式从 IP 地址转换为主机名的方法。
伪代码:
IPAddress ip = new IPAddress("192.168.190.62");
String host = ip.getHost();
System.out.println(host); //prints "access-console"
My hosts file (C:\WINDOWS\system32\drivers\etc\hosts) has a bunch of IP Address to host name mappings:
# Switches
192.168.200.254 sw-con-ctrl
192.168.201.253 sw-con-ctrl-2
192.168.201.254 sw-con-ctrl-1
# 192.168.188.1 sw-con-ctrl-ylw-1
# 192.168.189.1 sw-con-ctrl-blu
192.168.190.62 access-console
# Routers
192.168.21.1 rtr1
192.168.22.1 rtr2
I am trying to find a way to convert from an IPAddress to the HostName programmatically through Java APIs.
Pseudocode:
IPAddress ip = new IPAddress("192.168.190.62");
String host = ip.getHost();
System.out.println(host); //prints "access-console"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
输出 :
Output :
我尝试了此处中的代码,它有效。即:
I tried the code from here and it works. Namely:
当不需要反向查找时,这就像 javadocs 所说的仅在本地工作:
如果提供了文字 IP 地址,则仅检查地址格式的有效性。
如果有人知道一种不使用第三方 jar 进行远程查找的方法......
This works as the javadocs say only local when no reverse lookup is needed:
If a literal IP address is supplied, only the validity of the address format is checked.
If someone know a way without using third party jars to do the remote lookup...
InetAddress
类。我想你会想要 < code>getHostName 或getCanonicalHostName
,具体取决于您的需要。There are methods in the
InetAddress
class for that. I think you'll want eithergetHostName
orgetCanonicalHostName
, depending on your need.