我有DNS服务器IP地址和主机名。
使用Java,如何使用IP地址和主机名从DNS服务器返回该主机名的IP地址?
请查看InetAddress
和getHostAddress()
方法。
InetAddress address = InetAddress.getByName("www.example.com");
System.out.println(address.getHostAddress());
getHostAddress()
时,InetAddress
应该获取DNS解析的地址。但我不确定是否可以强制它使用特定的DNS服务器。 - thegrinner你可以像这样做:
for(InetAddress addr : InetAddress.getAllByName("stackoverflow.com"))
System.out.println(addr.getHostAddress());
InetAddress address = InetAddress.getByName("www.yahoo.com");
System.out.println(address.getHostAddress());
System.out.println(address.getHostName());
根据以上所有建议,您可以使用InetAddress.getByName("hostName")
,但这可能会给您一个缓存的IP。请阅读Java文档以获取相关信息。如果您想从DNS中获取IP,可以使用以下方法:
InetAddress[] ipAddress = DNSNameService.lookupAllHostAddr("hostName");
dig <hostname>
是什么意思? - ceejayoz