1.InetAddress类
Internet上的主机有两种方式表示地址:
①域名(hostName):www.baidu.com
②IP 地址(hostAddress):14.215.177.38
InetAddress类主要表示IP地址,两个子类:Inet4Address、Inet6Address
InetAddress 类对象含有一个 Internet 主机地址的域名和IP地址:
www.baidu.com 和 14.215.177.38
域名容易记忆,当在连接网络时输入一个主机的域名后,域名服务器(DNS) 负责将域名转化成IP地址,这样才能和主机建立连接。 -------域名解析
InetAddress类创建实例的方法:
- static InetAddress getByName(String host):通过域名创建InetAddress对象
- static InetAddress[] getAllByName(String host):获取一个包含该域名所对应的所有因特网地址的数组。
- static InetAddress getLocalHost():为本地主机创建一个InetAddress对象。
常用的实例方法: - String getHostName():返回域名;
- String getHostAddress():返回IP;
InetAddress address = InetAddress.getByName("www.baidu.com");
address.getHostName();//www.baidu.com
address.getHostAddress();//39.156.66.14
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
//[www.baidu.com/39.156.66.14, www.baidu.com/39.156.66.18]
2. Socket--客户端套接字
Socket构造函数:
- public Socket(String host, int port)
- public Socket(InetAddress address, int port)
通过域名和端口号建立一个套接字。
套接字超时
从套接字读取信息时,在有数据可供访问之前,读操作将会被阻塞。如果此时主机不可达,那么应用将要等待很长时间。所以对不同的应用,应该设置确定合理的超时值。
- synchronized void setSoTimeout(int timeout):设置套接字读请求的阻塞时间。如果超出给定时间,抛出InterruptedIOException异常。
Socket socket = new Socket("www.baidu.com",13);
socket.setSoTimeout(1000);//超时时间:10秒
另外一种情况,构造器:Socket(String host,int port)会一直无限期阻塞下去,直到建立了到达主机的初试连接为止。
可以通过以下方法解决:
Socket s = new Socket();
s.connect(new InetSocketAddress(host,port),timeout);
- void connect(SocketAddress endpoint):将套接字连接到给定地址。
- void connect(SocketAddress endpoint, int timeout):将套接字连接到给定地址。如果超出给定时间,则抛出一个InterruptedIOException异常。
- void bind(SocketAddress bindpoint):绑定给定的地址。
- boolean isConnected()
- boolean isClosed()
- synchronized void close()