InetAddress类
为了方便我们对IP地址的获取和操作,Java提供了一个类InetAddress供我们使用
InetAddress类在java.net包下。该类是一个具体类。该类继承了Object类,该类实现了Serializable
该类表示Internet协议的地址即IP地址,即该类表示的是IP地址的对象
该类没有构造方法,该类的大部分方法都不是静态的。解决:该类一定会有一种静态的方式得到该类的对象,如下的静态方法: static InetAddress getByName(String host) 根据主机名称确定主机的IP地址
还需要掌握两个非静态方法,如下: getHostAddress() 返回文本表示中的IP地址字符串。 getHostName() 获取此IP地址的主机名
InetAddress类的练习
package ch22;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
//static InetAddress getByName(String host) 根据主机名称确定主机的IP地址
//getHostAddress() 返回文本表示中的IP地址字符串。
//getHostName() 获取此IP地址的主机名
public class a_4_1测试 {
public static void main(String[] args) throws UnknownHostException {
//得到InetAddress的对象。通过主机名得到得到InetAddress的对象。建议使用这种方式得到InetAddress的对象
InetAddress address = Inet4Address.getByName("焕发a青春"); //getByName报红线,选中getByName,按Alt+Enter,选Add...
//获取主机名,即机器名
String name = address.getHostName();
//获取IP地址的字符串
String ip = address.getHostAddress();
System.out.println("主机名:"+name);
System.out.println("IP地址:"+ip);
System.out.println("----------------------------");
//----------------------------------------------------------------------------------------------------------
//得到InetAddress的对象。通过Ip地址得到InetAddress的对象
InetAddress address2 = Inet4Address.getByName("10.99.20.3");
//获取主机名,即机器名
String name2 = address2.getHostName();
//获取IP地址的字符串
String ip2 = address2.getHostAddress();
System.out.println("主机名:"+name2);
System.out.println("IP地址:"+ip2);
}
}