我想在我的程序中根据给定的IP地址找到主机名。
如果可以,请提供代码。谢谢。
是的,这是可能的。
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
}
}
类似这样的内容应该会指引您朝着正确的方向前进:
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();
}
}
}
嘿,我正在使用上述方法,但是getHostName()方法没有返回给定IP的主机名。
请看代码:
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);
}
InetAddress
类的 getHostName()
方法。试一试....
System.out.println(InetAddress.getByName("IP_ADDR").getHostName());