简体   繁体   English

Java中主机名的IP地址?

[英]IP Address to Hostname in Java?

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"

I tried the code from here and it works.我从这里尝试了代码并且它有效。 Namely:即:

  InetAddress addr = InetAddress.getByName("192.168.190.62");
  String host = addr.getHostName();
  System.out.println(host);

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 进行远程查找的方法...

There are methods in the InetAddress class for that. InetAddress类中InetAddress方法。 I think you'll want either getHostName or getCanonicalHostName , depending on your need.我认为您需要getHostNamegetCanonicalHostName ,具体取决于您的需要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM