使用InetAddress类的getHostName方法

InetAddress---表示互联网协议(IP)地址

我所知道的,常用的得到InetAddress实例的方法有三种:

//直接获取,获取的是本机:

    InetAddress.getLocalHost();

//根据域名获取:如果参数为null,获得的是本机的IP地址

    InetAddress.getByName("www.oracle.com");  

                    .getAllByName();

                    .getByAddress();

//根据ip获取:

    InetAddress.getByName("23.13.187.107"); 

                    .getAllByName();

                    .getByAddress();            

getHostName的时候,,

    第一种,第二种方式获取InetAddress对象调用getHostName获取域名/主机名的时候,直接返回,不需要经过dns。。

    根据ip得到的InetAddress对象,调用getHostName获取域名/主机名的时候,需要dns进行解析匹配,所以耗时较长。。如果没有找到,直接返回ip

案例:

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

/**
 * 关于java 操作localhost的测试
 *
 * @author LZJ
 * @create 2018-03-27 17:59
 **/
public class InetAddressTest {
    public static void main(String[] args){
        try {
            long start = System.currentTimeMillis();
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println("localHost:" + localHost);
            System.out.println("hostName:" + localHost.getHostName());
            System.out.println("hostAddress:" + localHost.getHostAddress());
            System.err.println("耗费时间:" + (System.currentTimeMillis() - start) + "ms");
            System.out.println("====================");

            InetAddress byName = InetAddress.getByName("www.oracle.com");
            System.out.println("byName:" + byName);
            System.out.println("hostName:" + byName.getHostName());
            System.out.println("hostAddress:" + byName.getHostAddress());
            System.err.println("耗费时间:" + (System.currentTimeMillis() - start) + "ms");
            System.out.println("====================");

            InetAddress byIp = InetAddress.getByName("23.13.187.107");
            System.out.println("byIp:" + byIp);
            System.out.println("hostName:" + byIp.getHostName());
            System.out.println("hostAddress:" + byIp.getHostAddress());
            System.err.println("耗费时间:" + (System.currentTimeMillis() - start) + "ms");


        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
结果:
使用InetAddress类的getHostName方法_第1张图片

        



你可能感兴趣的:(java基础,网络)