Java学习之网络编程--InetAddress,InetSocketAddress
1.InetAddress:封装计算机的IP地址和DNS,没有端口静态方法货物对象
InetAddress.getLocalHost();
InetAddress.getByName(域名|IP)
方法
getHostAddress(); 返回IP地址
getHostName(); 返回域名|本机为计算机名
创建对象:
InetSocketAddress(String hostname,int port)
InetSocketAddress(InetAddress addr,int port)
方法:
getAddress()
getHostName()
InetAddress.getLocalHost();
InetAddress.getByName(域名|IP)
方法
getHostAddress(); 返回IP地址
getHostName(); 返回域名|本机为计算机名
public static void main(String[] args) throws UnknownHostException { //用getLocalHost方法创建InetAddress对象 InetAddress addr = InetAddress.getLocalHost(); System.out.println(addr.getHostAddress());//返回IP System.out.println(addr.getHostName());//返回主机名 //根据域名得到InetAddress对象 addr = InetAddress.getByName("www.163.com"); System.out.println(addr.getHostAddress());//返回163的IP地址 System.out.println(addr.getHostName());//返回域名 addr = InetAddress.getByName("60.207.246.98"); System.out.println(addr.getHostAddress());//返回163的IP地址 System.out.println(addr.getHostName());//返回域名,如果IP解析则返回域名,不解析还是返回IP }2.InetSocketAddress
创建对象:
InetSocketAddress(String hostname,int port)
InetSocketAddress(InetAddress addr,int port)
方法:
getAddress()
getHostName()
public static void main(String[] args) throws UnknownHostException { InetSocketAddress addr = new InetSocketAddress("localhost",8888); addr = new InetSocketAddress(InetAddress.getByName("127.0.0.1"),9999); System.out.println(addr.getHostName()); System.out.println(addr.getPort()); InetAddress add = addr.getAddress(); System.out.println(add.getHostAddress()); System.out.println(addr.getHostName()); }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。