java實現Ping示例代碼
這個示例不是真正實現ping用來檢測是否alive,因為Socket類沒有足夠操作的權限,但是我們可以模仿ping,通過"echo port"實現,在server端,"echo port"端口一般是7,我們往這個端口寫入一個字符串,然后這個server會返回這個字符串。
import java.io.; import java.net.;public class PseudoPing { public static void main(String args[]) { try { Socket t = new Socket(args[0], 7); DataInputStream dis = new DataInputStream(t.getInputStream()); PrintStream ps = new PrintStream(t.getOutputStream()); ps.println("Hello"); String str = dis.readLine(); if (str.equals("Hello")) System.out.println("Alive!") ; else System.out.println("Dead or echo port not responding");
t.close(); } catch (IOException e) { e.printStackTrace();} } } }</pre>ps.從JDK1.5之后,java.net.InetAddress.isReachable(int)可以用來檢測一個服務器是否alive狀態。
import java.io.*; import java.net.*; public class ReachableTest { public static void main(String args[]) { try { InetAddress address = InetAddress.getByName("web.mit.edu"); System.out.println("Name: " + address.getHostName()); System.out.println("Addr: " + address.getHostAddress()); System.out.println("Reach: " + address.isReachable(3000)); } catch (UnknownHostException e) { System.err.println("Unable to lookup web.mit.edu"); } catch (IOException e) { System.err.println("Unable to reach web.mit.edu"); } } }
如果有權限的話isReachable()方法會使用ICMP ECHO REQUESTs;沒權限的話會嘗試在向目標主機的端口號7上建立tcp連接。 不過多數站點主機都禁用這個請求。