java网络编程学习笔记
一、InetAddrress
首先InetAddress有5个静态方法可以得到InetAddress的对象
getAllByName(String host) 在给定主机名的情况下,根据系统上配置的名称服务返回其 IP 地址所组成的数组
getByAddress(byte[] addr) 在给定原始 IP 地址的情况下,返回 InetAddress 对象
getByAddress(String host, byte[] addr) 根据提供的主机名和 IP 地址创建 InetAddress。
getByName(String host) 在给定主机名的情况下确定主机的 IP 地址。
getLocalHost() 返回本地主机。
InetAddress add=InetAddress.getLocalHost();
通过getLocalHost()方法,可以得到这样格式的InetAddress:USER-20140929ZB/10.88.147.147
是因为在InetAddress中对toString()重写了,代码如下:
public String toString() { String hostName = holder().getHostName(); return ((hostName != null) ? hostName : "") + "/" + getHostAddress(); }
即不管有没有hostname,都会有"/"和IP地址。
public static void main(String []args) { try{ InetAddress[] address=InetAddress.getAllByName(args[0]); for(InetAddress i:address){ System.out.println((i.toString().split("/"))[1]); } }catch(Exception e){ System.out.println(e.getMessage()); } }
通过上一段的代码我们写入参数: "www.baidu.com" 输出的ip地址为:
180.149.131.205
180.149.131.236
在浏览器一栏输入这两个ip地址均能访问百度首页,但是,如果我们将参数写为:"www.csdn.net"得到的ip地址直接使用将不能访问csdn。报错为:
406 Not Acceptable
我们发现这并不是404 Not Found错误,说明www.csdn.net的服务器通过检测Host字段防止直接使用ip访问

浙公网安备 33010602011771号