源代码:
package com.bjsxt.TcpIp; import java.net.InetAddress; import java.net.UnknownHostException; public class InetDemo02 { public static void main(String[] args) throws UnknownHostException { InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com"); byte[] bytes1 = inetAddress1.getAddress(); System.out.print("inetAddress1.getAddress(): "); for (byte b : bytes1) { System.out.print(b + ","); } System.out.println(); System.out.println("inetAddress1.getHostAddress(): " + inetAddress1.getHostAddress()); System.out.println("inetAddress1.getHostName(): " + inetAddress1.getHostName()); System.out.println("====================================="); InetAddress inetAddress2 = InetAddress.getByAddress(bytes1); System.out.println("inetAddress2.getHostAddress(): " + inetAddress2.getHostAddress()); System.out.println("inetAddress2.getHostName(): " + inetAddress2.getHostName()); System.out.println("====================================="); } }
运行结果:
inetAddress1.getAddress(): -73,-24,-25,-82, inetAddress1.getHostAddress(): 183.232.231.174 inetAddress1.getHostName(): www.baidu.com ===================================== inetAddress2.getHostAddress(): 183.232.231.174 inetAddress2.getHostName(): 183.232.231.174 =====================================
疑问:
为什么 inetAddress2.getHostName() 获取的不是“www.baidu.com”呢?
inetAddress2是通过 getByAddress 获取的,用的就是 inetAddress1 的 getAddress 的返回值,我以为应该指向是相同的,实际运行获取的 getHostAddress() 相同,但是获取的 getHostName() 不同。
通过getByAddress(), 要填入什么参数,才能有 getHostName() 来获得 "www.baidu.com"呢?