解析主机名的IP地址

Dar*_*ter 80 java

我有DNS服务器IP地址和主机名.

使用Java,如何使用IP地址和主机名找到该DNS服务器返回的主机名的IP地址?

the*_*ner 116

看看InetAddressgetHostAddress()方法.

InetAddress address = InetAddress.getByName("www.example.com"); 
System.out.println(address.getHostAddress()); 
Run Code Online (Sandbox Code Playgroud)

  • @DarkMatter:当你要求`getHostAddress()`时,`InetAddress`应该得到DNS解析的地址.我不确定你是否可以强迫它使用*特定的*DNS服务器. (3认同)

Wal*_*uch 27

你可以这样做:

for(InetAddress addr : InetAddress.getAllByName("stackoverflow.com"))
    System.out.println(addr.getHostAddress());
Run Code Online (Sandbox Code Playgroud)


Abh*_*asu 9

您可以使用InetAddress.试试下面的代码,

InetAddress address = InetAddress.getByName("www.yahoo.com");
System.out.println(address.getHostAddress());
System.out.println(address.getHostName());
Run Code Online (Sandbox Code Playgroud)