今天在寫 Java 的時候,遇到問題跑去問 TonyQ 兄,他丟了一個網址給我,剛剛測試過了,還漫好用的,紀錄一下 模擬 ping 的實現
import java.io.*; import java.net.*; public class PseudoPing { public static void main(String args[]) { try { InetAddress address = InetAddress.getByName(args[0]); System.out.println(address.isReachable(5000)); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
模擬 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) { } }參考網站: