Java Socket通信之InetAddress类的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huiting_liu/article/details/68083238
  1. InetAddress 类用于标识网络上的硬件资源,表示互联网协议(IP)地址。

  2. InetAddress对象的获取
    InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:

方法 说明
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() 返回本地主机

Example1: 通过getByName(String host)方法获取实例

//创建InetAddress对象
InetAddress  address2=InetAddress.getByName("PC-PC");
//获得该对象的主机名
System.out.println("计算机名:"+address2.getHostName());
//获得该对象的主机地址
System.out.println("IP地址:"+address2.getHostAddress());

这里写图片描述

Example2:通过getLocalHost()方法获取本机的InetAddress实例

//获取本机的InetAddress实例
InetAddress address= InetAddress.getLocalHost();
System.out.println("计算机名:"+address.getHostName());
System.out.println("IP地址:"+address.getHostAddress());
//获取字节数组形式IP地址
byte[] bytes=address.getAddress();
System.out.println("字节数组形式的IP:"+Arrays.toString(bytes));
//直接输出InetAddress对象
System.out.println(address);

这里写图片描述

猜你喜欢

转载自blog.csdn.net/huiting_liu/article/details/68083238