一.模拟ping的实现
利用InetAddress的isReachable方法可以实现ping的功能,里面参数设定超时时间,返回结果表示是否连上。try ... {
InetAddress address = InetAddress.getByName("192.168.0.113");
System.out.println(address.isReachable(5000));
} catch (UnknownHostException e) ... {
e.printStackTrace();
} catch (IOException e) ... {
e.printStackTrace();
}
二.模拟telnet的实现
利用Socket的connect(SocketAddress endpoint, int timeout)方法可以实现telnet的功能,如果catch到异常说明telnet失败
Socket server = null ;
try ... {
server = new Socket();
InetSocketAddress address = new InetSocketAddress("192.168.0.201",8899);
server.connect(address, 5000);
} catch (UnknownHostException e) ... {
System.out.println("telnet失败");
} catch (IOException e) ... {
System.out.println("telnet失败");
} finally ... {
if(server!=null)
try ...{
server.close();
} catch (IOException e) ...{
}
}