Java中主机名的IP地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3371879/
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
IP Address to Hostname in Java?
提问by mainstringargs
My hosts file (C:\WINDOWS\system32\drivers\etc\hosts) has a bunch of IP Address to host name mappings:
我的主机文件(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
I am trying to find a way to convert from an IPAddress to the HostName programmatically through Java APIs.
我试图找到一种通过 Java API 以编程方式从 IPAddress 转换为 HostName 的方法。
Pseudocode:
伪代码:
IPAddress ip = new IPAddress("192.168.190.62");
String host = ip.getHost();
System.out.println(host); //prints "access-console"
采纳答案by user85509
回答by Bill the Lizard
There are methods in the InetAddress
class for that. I think you'll want either getHostName
or getCanonicalHostName
, depending on your need.
类中有一些方法InetAddress
。我想你会想要getHostName
或getCanonicalHostName
,这取决于你的需要。
回答by RudeUrm
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.
这就像 javadocs 在不需要反向查找时所说的那样只在本地工作:如果提供了文字 IP 地址,则只检查地址格式的有效性。
If someone know a way without using third party jars to do the remote lookup...
如果有人知道不使用第三方 jar 进行远程查找的方法...
回答by Fridjato Part Fridjat
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main02{
public static void main(String[]args) throws UnknownHostException{
InetAddress ia = InetAddress.getByName("46.228.47.114");
System.out.println(ia.getHostName());
}
}
Output :
输出 :
ir2.fp.vip.ir2.yahoo.com
ir2.fp.vip.ir2.yahoo.com