网络编程 p2 InetAddress

InetAddress类

相关方法:

  1. getLocalHost():获取本机InetAddress对象;
  2. getByName():根据指定主机名/域名获取IP地址对象;
  3. getHostName():获取Inet Address对象的主机名;
  4. getHostAddress():获取InerAddress对象的地址;

代码演示:

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: 86199
 * @date: 2023/5/14 16:19
 * @description: 演示InetAddress类的使用
 */
public class API_ {
    public static void main(String[] args) throws UnknownHostException {

        //1. 获取本机的InetAddress对象
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println("localHost = " + localHost);

        //2. 根据指定的主机名,获取 InetAddress对象
        InetAddress host1 = InetAddress.getByName("LAPTOP-6CFCSNPH");
        System.out.println("host1 = " + host1);

        //3. 根据域名返回 InetAddress对象
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        System.out.println("host2 = " + host2);//www.baidu.com/110.242.68.4

        //4. 通过 InetAddress对象 获取地址
        String hostAddress = host2.getHostAddress();//IP地址
        System.out.println("host2的 ip = " + hostAddress);

        //5. 通过 InetAddress对象 获取 主机名或域名
        String hostName = host2.getHostName();
        System.out.println("host2 对应的主机名/域名 = " + hostName);
    }
}

/*
运行结果:
localHost = LAPTOP-6CFCSNPH/xx.xx.xx.xx
host1 = LAPTOP-6CFCSNPH/xx.xx.xx.xx
host2 = www.baidu.com/110.242.68.3
host2的 ip = 110.242.68.3
host2 对应的主机名/域名 = www.baidu.com
*/

posted @ 2023-07-17 20:38  凉白茶  阅读(4)  评论(0编辑  收藏  举报