1、使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIP {
public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getByName("www.baidu.com");//根据主机名www.baidu.com来获取其相关的地址信息并保存在address
}
catch (UnknownHostException e) {
System.exit(2);
}
System.out.println(address.getHostName() + "=" + address.getHostAddress());
System.exit(0);
}
}
运行结果为:
www.baidu.com=183.232.231.173
但要注意的是baidu的主机不止一台,会经常改变。
使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名
import java.net.InetAddress;
public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();//获取本机的相关信息并保存在addr
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}
运行结果为:
Local HostAddress: 192.168.88.1
Local host name: MrBread