InetAddress类:封装IP地址或域名
InetAddress类的两个子类:
- Inet4Address:封装4个字节的IP地址
- Inet6Address:封装6个字节的IP地址
方法 | 功能 |
public static InetAddress getLocalHost() | 获得本地主机对应的InetAddress对象 |
public static InetAddress getByName(String host) | 根据指定的IP地址或域名来获得对应的InetAddress对象 |
public static InetAddress[ ] getAllByName(String host) | 根据主机获得具有相同名称的一组InetAddress对象 |
public static InetAddress getByAddress(byte[ ] bt) | 获得字节数组所封装的IP地址对应的InetAddress对象 |
|
|
public String getCanonicalHostName() | 获得IP地址的全限定域名 |
public bytes[ ] getHostAddress() | 获取InetAddress对象对应的IP地址 |
public String getHostName() | 获取InetAddress对象对应的主机名称 |
public boolean isReachable(int timeout) | 判断是否可以到达该地址 |
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) {
try {
// 1.获得本地主机对应的InetAddress对象
InetAddress inetaddress1 = InetAddress.getLocalHost();
System.out.println("Local name:" + inetaddress1.getHostName());
System.out.println("Local address:" + inetaddress1.getHostAddress());
System.out.println("Local full:" + inetaddress1.getCanonicalHostName());
System.out.println("Local toString:" + inetaddress1.toString());
System.out.println("Local ip:" +inetaddress1);
System.out.println("Local isreachable:" + inetaddress1.isReachable(5));
System.out.println("————————————————————————————————————");
// 2.获得指定域名的InetAddress对象
InetAddress inetaddress2 = InetAddress.getByName("wwww.baidu.com");
System.out.println("Local name:"+inetaddress2.getHostName());
System.out.println("Local address:"+ inetaddress2.getHostAddress());
System.out.println("Local full:"+ inetaddress2.getCanonicalHostName());
System.out.println("Local toString:"+ inetaddress2.toString());
System.out.println("Local ip:"+ inetaddress2);
System.out.println("Local reachable:"+ inetaddress2.isReachable(5));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}