java为网络提供了java.net包,该包下的URL和URLConnection等类提供了已编程方式访问的web服务的功能。java提供了InetAddress类来代表ip地址。 IntetAddress并没有构造器,而是提供了如下的两个静态的方法来获取InetAddress实例。 getByName():根据主机获取对应的InetAddrress对象。 getByAddress():根据原始的IP地址获取对应的InetAddress()对象 他提供了三个方法来获取InetAddress实例对应的ip地址和主机名: ①String getCanonicalHostName():获取此ip地址的主机名。 ②String getHostAddress():获取ip地址的字符串 ③String getHostName():获取ip地址的主机别名(①和③的区别http://www.educity.cn/java/466142.html) InetAddress还提供了一个isReachable(timeout)的方法,用于测试是否可以到达该地址(主机)。防火墙或者服务器配置可能阻塞请求。

public class InetAddressDemo {

public static void main(String[] args) {
try {
// 获取本机的ip地址和主机名
InetAddress indress = InetAddress.getLocalHost();
String hostName = indress.getHostName();
String hostAddress = indress.getHostAddress();
System.out.println("本机主机名:" + hostName + "\n本机的ip: " + hostAddress);
//2S内是否能到达
System.out.println("isReachable\t"+indress.isReachable(2000));
//通过主机名获取 InetAddress()实例
InetAddress byHost = InetAddress.getByName("www.baidu.com");
System.out.println(byHost);
System.out.println("百度主机: "+byHost.getHostName() + "\n百度ip: " + byHost.getHostAddress());

//通过ip获取InetAddress实例
InetAddress byAddress = InetAddress.getByAddress(new byte[]{127,0,0,1});
System.out.println("ip的主机: "+byAddress.getHostName()+" ip的ip: "+byAddress.getHostAddress());

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

控制台的输出:

本机主机名:PC201606021052
本机的ip: 192.168.1.102
isReachable true
www.baidu.com/61.135.169.125
百度主机: www.baidu.com
百度ip: 61.135.169.125
ip的主机: 127.0.0.1 ip的ip: 127.0.0.1