建筑网站建设案例天津市建设工程信息网站
IP
简单讲解InetAddress类
先记住一个id地址:127.0.0.1,这是本机的ip地址,之后的笔记中会常常出现。
InetAddress类没有构造方法,获得这个类的对象是通过调用InetAddress类的静态方法实现的。
示例代码
package Net_Study;import java.net.InetAddress;
import java.net.UnknownHostException;public class TestInetAddress {public static void main(String[] args) {try {// 查询本机ip地址InetAddress addr1 = InetAddress.getByName("127.0.0.1");System.out.println(addr1);InetAddress addr2 = InetAddress.getLocalHost();System.out.println(addr2);InetAddress addr3 = InetAddress.getByName("localhost");System.out.println(addr3);// 查询网站ip地址InetAddress addr4 = InetAddress.getByName("www.baidu.com");System.out.println(addr4);// 常用方法// 返回规范的名字——ipSystem.out.println(addr4.getCanonicalHostName());// 返回ipSystem.out.println(addr4.getHostAddress());// 返回域名,或者自己电脑的名字// 网站一般返回域名System.out.println(addr4.getHostName());// 本机一般返回自己电脑的名字System.out.println(addr1.getHostName());} catch (UnknownHostException e) {throw new RuntimeException(e);}}
}
运行结果:
/127.0.0.1
小琦/10.84.34.66
localhost/127.0.0.1
www.baidu.com/153.3.238.127
153.3.238.127
153.3.238.127
www.baidu.com
localhost
代码逐行解释及输出结果分析
1. 查询本机 IP 地址
// 查询本机ip地址
InetAddress addr1 = InetAddress.getByName("127.0.0.1");
System.out.println(addr1);
InetAddress.getByName("127.0.0.1"):通过getByName方法根据指定的 IP 地址字符串获取InetAddress对象。127.0.0.1是本地回环地址,用于测试本地网络连接。- 输出结果
/127.0.0.1:InetAddress对象的toString()方法默认输出格式为/后面跟着 IP 地址。
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println(addr2);
InetAddress.getLocalHost():返回本地主机的InetAddress对象。- 输出结果
小琦/10.84.34.66:小琦是你的计算机名,10.84.34.66是你当前计算机在局域网中的 IP 地址。
InetAddress addr3 = InetAddress.getByName("localhost");
System.out.println(addr3);
InetAddress.getByName("localhost"):根据主机名localhost获取InetAddress对象,localhost通常解析为127.0.0.1。- 输出结果
localhost/127.0.0.1:主机名localhost对应的 IP 地址是127.0.0.1。
2. 查询网站 IP 地址
// 查询网站ip地址
InetAddress addr4 = InetAddress.getByName("www.baidu.com");
System.out.println(addr4);
InetAddress.getByName("www.baidu.com"):根据域名www.baidu.com获取对应的InetAddress对象,该方法会通过 DNS(域名系统)解析域名得到对应的 IP 地址。- 输出结果
www.baidu.com/153.3.238.127:域名www.baidu.com解析后的 IP 地址是153.3.238.127。
3. 常用方法
// 返回规范的名字——ip
System.out.println(addr4.getCanonicalHostName());
addr4.getCanonicalHostName():返回主机的规范名称,通常是经过 DNS 解析后的完全限定域名(FQDN),对于百度的 IP 地址,这里直接返回了对应的 IP 地址153.3.238.127,这可能是因为 DNS 配置或解析的结果。
// 返回ip
System.out.println(addr4.getHostAddress());
addr4.getHostAddress():返回InetAddress对象对应的 IP 地址字符串,输出为153.3.238.127。
// 返回主机名,网站返回域名
System.out.println(addr4.getHostName());
addr4.getHostName():返回主机名,如果是通过域名获取的InetAddress对象,通常会返回该域名,所以输出为www.baidu.com。
// 本机一般返回自己电脑的名字
System.out.println(addr1.getHostName());
addr1.getHostName():对于127.0.0.1对应的InetAddress对象,返回的主机名是localhost。
