InetAddress类
InetAddress
类没有提供公共的构造器,而是提供了如下几个静态方法来获取InetAddress
实例
public static InetAddress getLocalHost()
public static InetAddress getByName(String host)
InetAddress
提供了如下几个常用的方法:
public String getHostAddress()
:返回 IP 地址字符串(以文本表现形式)。public String getHostName()
:获取此 IP 地址的主机名public boolean isReachable(int timeout)
:测试是否可以达到该地址
public class InetAddressTest {
public static void main(String[] args) {
try {
//InetAddress类代表着IP,一个IP地址对应一个InetAddress的实例
InetAddress inetAddress1 = InetAddress.getByName("192.168.244.1");
System.out.println(inetAddress1);
//通过域名获取IP地址
InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
System.out.println(inetAddress2);
//获取本机ip地址
InetAddress inetAddress3 = InetAddress.getLocalHost();
System.out.println(inetAddress3);
//获取本地回路地址,即127.0.0.1
InetAddress inetAddress4 = InetAddress.getLoopbackAddress();
System.out.println(inetAddress4);
System.out.println(inetAddress2.getHostName());
System.out.println(inetAddress2.getHostAddress());
try {
System.out.println(inetAddress2.isReachable(100));
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}