InetAddress

java.net.InetAddress:主要作用是封装 IP 及 DNS ,这个类没有构造方法

1、获取 InetAdderss 对象

  • InetAddress.getLocalHost():获得本机的 InetAddress 对象
  • InetAddress.getByName(“www.baidu.com”):根据域名得到 InetAddress 对象
  • InetAddress.getByName(“113.13.100.113”):根据 IP 得到 InetAddress 对象

2、获取主机地址

  • InetAddress.getHostAddress():获取主机地址字符串
  • InetAddress.getHostName():获取主机名称 ```java public class Demo { public static void main(String[] args) throws CharacterCodingException, UnknownHostException {

    1. // 1.获得本机的InetAddress对象
    2. InetAddress localHost = InetAddress.getLocalHost();
    3. print(localHost);
    4. // 2.通过域名获取InetAddress对象
    5. InetAddress baidu = InetAddress.getByName("www.baidu.com");
    6. print(baidu);
    7. // 3.通过IP获取InetAddress对象
    8. InetAddress inetAddress = InetAddress.getByName("14.215.177.38");
    9. print(inetAddress);

    }

    private static void print(InetAddress inetAddress) {

    1. System.out.println(inetAddress.getHostName());
    2. System.out.println(inetAddress.getHostAddress());

    } }

// 输出: DESKTOP-NJ2O5D6 172.30.80.1 // 获取本机的IP地址 www.baidu.com 14.215.177.38 14.215.177.38 // DNS不给解析,返回IP地址本身 14.215.177.38

  1. <a name="KyeT6"></a>
  2. #### InetSocketAddress
  3. InetSocketAddress类的主要作用是封装端口,继承了 InetAddress 类
  4. InetSocketAddress类的构造方法:
  5. - InetSocketAddress(InetAddress addr, int port):根据 IP 地址和端口号创建套接字地址
  6. - InetSocketAddress(String hostname, int port):根据主机名和端口号创建套接字地址
  7. InetSocketAddress类的常用方法:
  8. - getAddress():获取 InetAddress
  9. - getPort():获取端口号
  10. - toString():构造 InetSocketAddress 的字符串形式,主机名/IP:端口号
  11. - getHostName():获取主机名3
  12. ```java
  13. InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 10000);
  14. System.out.println(address.getPort()); // 10000
  15. System.out.println(address.getHostName()); // DESKTOP-NJ2O5D6
  16. System.out.println(address.getAddress()); // DESKTOP-NJ2O5D6/172.30.80.11
  17. System.out.println(address.toString()); // DESKTOP-NJ2O5D6/172.30.80.11:10000