isReachable(int timeout) 测试是否能达到特定IP地址
isReachable(NetworkInterface netif,int ttl,int timeout)测试是否能达到特定IP地址,并且制定特定的NetworkInterface,ttl表示路由过程中的最大跳数,timeout是超时时间。一个简单的例子如下:
package org.dakiler.javanet.chapter1;
import java.net.InetAddress;
public class Example4
{
public static void main(String args[])throws Exception
{
InetAddress address1=InetAddress.getLocalHost();
InetAddress address2=InetAddress.getByName("www.baidu.com");
System.out.println(address1.isReachable(5000));
System.out.println(address2.isReachable(5000));
}
}
分别测试本机是否可达以及www.baidu.com是否可达。运行的结果是:
true
false
感觉奇怪么,前者是正常的,但是按理说www.baidu.com应该也是可达的,实际确实false,这个原因是因为isReachable的实现,通常是ICMP ECHO Request 或是尝试使用目标主机上的端口7进行连接,很有可能被防火墙拦截,所以会访问不到。
如果要TELNET的话,会比较准确,比如以下代码
// TODO Auto-generated method stub
Socket server = null;
try {
server = new Socket();
InetSocketAddress address = new InetSocketAddress("bbs.sysu.edu.cn",23);
server.connect(address, 5000);
System.out.println("ok!");
}
catch (UnknownHostException e) {
System.out.println("wrong!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("wrong");
e.printStackTrace();
}