InetAddress
java.net.InetAddress:主要作用是封装 IP 及 DNS ,这个类没有构造方法
1、获取 InetAdderss 对象
- InetAddress.getLocalHost():获得本机的 InetAddress 对象
- InetAddress.getByName(“www.baidu.com”):根据域名得到 InetAddress 对象
- InetAddress.getByName(“113.13.100.113”):根据 IP 得到 InetAddress 对象
2、获取主机地址
- InetAddress.getHostAddress():获取主机地址字符串
InetAddress.getHostName():获取主机名称 ```java public class Demo { public static void main(String[] args) throws CharacterCodingException, UnknownHostException {
// 1.获得本机的InetAddress对象InetAddress localHost = InetAddress.getLocalHost();print(localHost);// 2.通过域名获取InetAddress对象InetAddress baidu = InetAddress.getByName("www.baidu.com");print(baidu);// 3.通过IP获取InetAddress对象InetAddress inetAddress = InetAddress.getByName("14.215.177.38");print(inetAddress);
}
private static void print(InetAddress inetAddress) {
System.out.println(inetAddress.getHostName());System.out.println(inetAddress.getHostAddress());
} }
// 输出: DESKTOP-NJ2O5D6 172.30.80.1 // 获取本机的IP地址 www.baidu.com 14.215.177.38 14.215.177.38 // DNS不给解析,返回IP地址本身 14.215.177.38
<a name="KyeT6"></a>#### InetSocketAddressInetSocketAddress类的主要作用是封装端口,继承了 InetAddress 类InetSocketAddress类的构造方法:- InetSocketAddress(InetAddress addr, int port):根据 IP 地址和端口号创建套接字地址- InetSocketAddress(String hostname, int port):根据主机名和端口号创建套接字地址InetSocketAddress类的常用方法:- getAddress():获取 InetAddress- getPort():获取端口号- toString():构造 InetSocketAddress 的字符串形式,主机名/IP:端口号- getHostName():获取主机名3```javaInetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 10000);System.out.println(address.getPort()); // 10000System.out.println(address.getHostName()); // DESKTOP-NJ2O5D6System.out.println(address.getAddress()); // DESKTOP-NJ2O5D6/172.30.80.11System.out.println(address.toString()); // DESKTOP-NJ2O5D6/172.30.80.11:10000
