有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

网络编程“localhost”vs 127.0.0.1 java

Java将127.0.0.1作为InetAddress的IP地址。getByName(“本地主机”)。getHostAddress() 但是为什么java没有为InetAddress提供“localhost”。getByName(“127.0.0.1”)。获取主机名。对于后面的一个,我将“127.0.0.1”作为主机名。请澄清这一点


共 (1) 个答案

  1. # 1 楼答案

    ^{}州的javadoc

    The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

    所以它实际上并没有进入你的hosts文件(或DNS)来获取IP地址。它只是创建一个InetAddress对象,其中包含从您提供的String创建的主机名和地址

    第一个例子

    InetAddress.getByName("localhost").getHostAddress()
    

    假设你有一个hosts文件条目,比如

    127.0.0.1    localhost
    

    然后返回的InetAddress对象将包含该信息,即localhost的主机名和127.0.0.1的地址

    同样,如果你有

    1.2.3.4    this.is.a.name
    

    InetAddress localhost = InetAddress.getByName("this.is.a.name");
    

    返回的InetAddress将由主机名this.is.a.name和地址1.2.3.4构成,因为它实际上是去检查的