网络编程(二)InetAddress和InetSocketAddress
本节主要讲InetAddress和InetSocketAddress这两个类
InetAddress 封装计算机的IP地址和DNS,没有端口
1、静态方法获取对象 InetAddress
InetAddress.getLocalHost(); //返回本地主机。
InetAddress.getByName("www.baidu.com"); //在给定主机名的情况下确定主机的 IP 地址
InetAddress.getByName("127.0.0.1");
InetAddress获取IP地址和主机名的方法
获取IP地址getHostAddress()
获取主机名:getHostName()
一个例子,
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostName());
System.out.println(addr.getHostAddress());
输出:DESKTOP-8MK009T
192.168.71.1
上述没有对象InetAddress没有封装端口
封装了端口的类InetSocketAddress
获取InetSocketAddress的构造方法
该类常用的方法
一个例子:
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8080);
addr = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 8080);//另一种构造方法
String hostName = addr.getHostName();
int port = addr.getPort();
InetAddress address = addr.getAddress();
String sname = address.getHostName();
String saddress = address.getHostAddress();
System.out.println(hostName);
System.out.println(port);
System.out.println(sname);
System.out.println(saddress);
输出:
127.0.0.1
8080
127.0.0.1
127.0.0.1
InetSocketAddress(String hostname, int port)的源码
InetSocketAddress(InetAddress addr, int port)的源码
看源码发现InetSocketAddress(String hostname, int port) 的内部实现还是将hostname封装成了InetAddress
自学笔记,多有不足!!!