java 如何根据IP地址获取主机名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11806523/
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
How to get host name based on IP address?
提问by user14345
I want to find the Host Name based on the given IP address in my program. Is it possible to get it, if yes can you please provide the code. Thanks.
我想根据程序中给定的 IP 地址查找主机名。是否可以得到它,如果是,请提供代码。谢谢。
回答by
Yes, its possible.
是的,这是可能的。
import java.net.*;
public class HostName
{
public static void main(String args[])
{
InetAddress inetAddress =InetAddress.getByName("127.64.84.2");//get the host Inet using ip
System.out.println ("Host Name: "+ inetAddress.getHostName());//display the host
}
}
回答by ioreskovic
Something like this should point you in the right direction:
像这样的事情应该指向正确的方向:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class DNSLookup {
public static void main(String args[]) {
try {
InetAddress host;
if (args.length == 0) {
host = InetAddress.getLocalHost();
} else {
host = InetAddress.getByName(args[0]);
}
System.out.println("Host:'" + host.getHostName()
+ "' has address: " + host.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
回答by Shashank Kadne
You can use getHostName()
method of InetAddress
class.
您可以使用类的getHostName()
方法InetAddress
。
回答by Kumar Vivek Mitra
Try this out....
试试这个....
System.out.println(InetAddress.getByName("IP_ADDR").getHostName());
System.out.println(InetAddress.getByName("IP_ADDR").getHostName());
回答by geekR
Hey I m using above methods bt the getHostName() method is not returning the host name of given ip.
嘿,我正在使用上述方法 bt getHostName() 方法没有返回给定 ip 的主机名。
see code:
见代码:
try {
// This is ip of tutorialspoint.com
InetAddress addr2 = InetAddress.getByName("127.64.84.2");
op.setText("Host name is: "+addr2.getHostName());
}
catch ( UnknownHostException e3) {
op.setText("Error: Host not found" + e3);
}
回答by Pavan Birajdar
import java.net.*;
public class GetHostNameFromIPAddress {
public static void main(String[] args) {
try {
InetAddress inetAddr = InetAddress.getByName("163.53.76.55");
// Get the host name
String hostname = inetAddr.getHostName();
// Get canonical host name
String canonicalHostname = inetAddr.getCanonicalHostName();
System.out.println("Hostname: " + hostname);
System.out.println("Canonical Hostname: " + canonicalHostname);
}
catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}