InetAddress:封装计算机的IP地址和DNS,没有端口
InetAddress() { holder = new InetAddressHolder(); }
InetSocketAddress:封装计算机的IP地址和端口,从构造方法就能发现
private InetSocketAddressHolder(String hostname, InetAddress addr, int port) { this.hostname = hostname; this.addr = addr; this.port = port; }
package ghs.jute;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class InetAddressTest {
public static void main(String[] args) throws UnknownHostException {
try {
//InetAddress,封装计算机的IP地址和DNS,没有端口
System.out.println("========InetAddress封装计算机的IP地址和DNS,没有端口========");
// 使用getLocalHost方法为InetAddress创建对象;
InetAddress add = InetAddress.getLocalHost();//获得本机的InetAddress对象
System.out.println("获取主机Ip,InetAddress.getHostAddress:" + add.getHostAddress());//返回本机IP地址
System.out.println("获取主机名hostname,InetAddress.getHostName:" + add.getHostName());//输出计算机名
//根据域名(dns解析)得到InetAddress对象
add = InetAddress.getByName("www.baidu.com");
System.out.println("获取主机Ip,InetAddress.getHostAddress:" + add.getHostAddress());//返回百度服务器的IP地址
System.out.println("获取主机名hostname,InetAddress.getHostName:" + add.getHostName());//输出www.baidu.com;
//根据ip得到InetAddress对象;
add = InetAddress.getByName("111.13.100.91");
System.out.println("获取主机Ip,InetAddress.getHostAddress:" + add.getHostAddress());
//如果ip地址存在,并且DNS给你解析就会输出
System.out.println("获取主机名hostname,InetAddress.getHostName:" + add.getHostName());
//www.baidu.com,不给你解析就会返回这个IP本身;
System.out.println("========InetAddress封装计算机的IP地址和DNS,没有端口========");
System.out.println("========InetSocketAddress封装计算机的IP地址和端口========");
InetSocketAddress add1 = new InetSocketAddress("10.1.1.165", 2181);
System.out.println("InetSocketAddress.getHostName():" + add1.getHostName());
System.out.println("InetSocketAddress.getPort():" + add1.getPort());
System.out.println("========InetSocketAddress封装计算机的IP地址和端口========");
//根据InetSocketAddress获取InetAddress
System.out.println("========根据InetSocketAddress获取InetAddress========");
InetAddress addr = add1.getAddress();//获得端口的ip;
System.out.println(addr.getHostAddress());//返回ip;
System.out.println(addr.getHostName());//输出端口名;
System.out.println("========根据InetSocketAddress获取InetAddress========");
}catch(Exception e){
e.printStackTrace();
}
}
}
运行结果:
========InetAddress封装计算机的IP地址和DNS,没有端口========
获取主机Ip,InetAddress.getHostAddress:127.0.0.1
获取主机名hostname,InetAddress.getHostName:gaohuashui
获取主机Ip,InetAddress.getHostAddress:112.80.248.76
获取主机名hostname,InetAddress.getHostName:www.baidu.com
获取主机Ip,InetAddress.getHostAddress:111.13.100.91
获取主机名hostname,InetAddress.getHostName:111.13.100.91
========InetAddress封装计算机的IP地址和DNS,没有端口========
========InetSocketAddress封装计算机的IP地址和端口========
InetSocketAddress.getHostName():water.com
InetSocketAddress.getPort():2181
========InetSocketAddress封装计算机的IP地址和端口========
========根据InetSocketAddress获取InetAddress========
10.1.1.165
water.com
========根据InetSocketAddress获取InetAddress========