java中IP地址、主机名的获取

时间:2021-03-30 13:39:13
import java.net.InetAddress;
import java.net.UnknownHostException;
//public static InetAddress getByName(String host):根据主机名或者IP地址的字符串表示得到IP地址对象。
/*根据IP地址或主机名*/
public class InetAddressDemo {

public static void main(String[] args) throws UnknownHostException {
// TODO Auto-generated method stub
// for(int i=0; i<256;i++){
InetAddress address = InetAddress.getByName("wymA");   //根据主机名得到IP地址对象
String name = address.getHostName();
String ip = address.getHostAddress();
System.out.println(name+"---"+ip);

InetAddress address1 = InetAddress.getByName("WYM-PC");
String name1 = address1.getHostName();
String ip1 = address1.getHostAddress();
System.out.println(name1+"---"+ip1);

InetAddress address2 = InetAddress.getByName("Dell-PC");
String name2 = address2.getHostName();
String ip2 = address2.getHostAddress();
System.out.println(name2+"---"+ip2);
// }

}
}



/*
运行结果:
wymA---219.216.81.205
WYM-PC---169.254.188.97
Dell-PC---219.216.81.168
*/