Java为了跨平台,在网络应用通信时是不运行直接调用操作系统接口的,而是由java.net包来提供网络功能。下面我们来介绍几个java.net包中的常用类。
InetAddress的使用
作用:封装计算机的IP地址和DNS(没有端口信息)
注:DNS是Domain Name System,域名系统。
特点:这个类没有构造方法,如果要得到对象,只能通过静态方法:getLocalHost()、getByName()、getAllByName()、getAddress()、getHostName()
获取本机信息
获取本机信息需要使用getLocalHost方法创建InetAddress对象。getLocalHost()方法返回一个InetAddress对象,这个对象包含了本机的IP地址,计算机名等信息。
public class InetTest {
public static void main(String[] args)throws Exception{
//实例化InetAddress对象
InetAddress inetAddress = InetAddress.getLocalHost();
//返回当前计算机的IP地址
System.out.println(inetAddress.getHostAddress());
//返回当前计算机名
System.out.println(inetAddress.getHostName());
}
}
根据域名获取计算机的信息
根据域名获取计算机信息时需要使用getByName("域名")方法创建InetAddress对象。
public class InetTest2 {
public static void main(String[] args)throws Exception{
InetAdress inetAddress = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress.getHostAddress());
System.out.println(inetAddress.getHostName());
}
}
获取IP获取计算机的信息
根据IP地址获取计算机信息时需要使用getByName("IP")方法创建InetAddress对象。
public class InetTest3 {
public static void main(String[] args)throws Exception{
InetAddress inetAddress = new InetAddress.getByName("14.215.177.38");
System.out.println(inetAddress.getHostAddress());
System.out.println(inetAddress.getHostName());
}
}