首页 > 编程笔记 > Java笔记 阅读:21

Java InetAddress类用法详解(附带实例)

Java 提供了 InetAddress 类来代表 IP 地址,该类有两个子类,即 Inet4Address 类和 Inet6Address 类,它们分别代表 IPv4 和 IPv6 的地址。

InetAddress 类提供了 5 个静态方法来获取实例,如下表所示:

表:InetAddress 类的静态方法
方法 方法描述
static InetAddress[] getAllByName(String host) 通过主机名返回其所所有 IP 地址所组成的数组
static InetAddress getByAddress(byte[] addr) 通过原始 IP 地址返回 InetAddress 对象
static InetAddress getByAddress(String host, byte[] addr) 通过主机名和 IP 地址创建 InetAddress 对象
static InetAddress getByName(String host) 通过主机名确定主机的 IP 地址
static InetAddress getLocalHost() 返回本机的 IP 地址

另外,InetAddress 类还有一些常用方法,如下表所示:

方法 方法描述
String getCanonicalHostName() 通过 IP 地址返回全限定域名
String getHostAddress() 返回 InetAddress 实例对应的 IP 地址字符串
String getHostName() 返回此 IP 地址的主机名
boolean isReachable(int timeout) 判定指定时间内是否可以访问目标地址

接下来,通过案例来演示上述方法的使用:
import java.net.InetAddress;

public class Demo {
    public static void main(String[] args) throws Exception {
        // 先获取到本机的地址并打印
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println("本机地址为:" + localHost);
        // 如果只需要获取到本机的IP号,则需要用toHostName()方法
        System.out.println("获取本机IP为:" + localHost.getHostAddress());
        // 获取主机名为"c.biancheng.net"的InetAddress地址,并打印
        InetAddress address = InetAddress.getByName("c.biancheng.net");
        System.out.println(address);
        // 打印"C语言中文网"的IP地址
        System.out.println("C语言中文网的IP为:" + address.getHostAddress());
        // 打印"C语言中文网"的主机名
        System.out.println("C语言中文网的主机名为:" + address.getHostName());
        // 判断能否在3秒内进行访问
        System.out.println("3秒内可以访问:" + address.isReachable(3000));
    }
}
程序的运行结果如下:

本机地址为:PC-202006302049/192.168.145.199
获取本机IP为:192.168.145.199
c.biancheng.net/122.116.169.212
C语言中文网的IP为:122.116.169.212
C语言中文网的主机名为:c.biancheng.net
3秒内可以访问:true

程序中,先调用 getLocalHost() 方法获取本地 IP 地址对应的 InetAddress 实例并打印本机 IP 地址。然后根据主机名“c.biancheng.net”获得 InetAddress 实例,再打印出 InetAddress 实例对应的 IP 地址和主机名。最后判断 3 秒内是否可访问这个实例,并打印结果。

相关文章