http://www.jguru.com/faq/view.jsp?EID=9904Question  How do I use Java to ping a host?  
Topics  Java:API:Network  
Author  John Zukowski  
Created  Jan 29, 2000  Modified  Jan 10, 2001  
 Answer Ping uses the Internet Control Message Protocol (ICMP) described in RFC 792 (see http://www.faqs.org/rfcs/rfc792.html). The standard Java networking libraries do not support ICMP. Without using native code or an external program, your Java programs cannot ping anybody. Comments and alternative answers   You can implement similar functionality by commun...
Tim Rohaly, Jan 31, 2000You can implement similar functionality by communicating with the well-known echo service described by RFC 862. Echo lives at port 7 (UDP or TCP), but will work only if the host you are trying to connect to implements it. Alternatively, you could implement the echo service yourself (in Java) and install it on the hosts you wish to contact.  

解决方案 »

  1.   

    http://www.io.com/~maus/jnetfaq.htmlWhy can't I write ping in Java?
    Ping requires ICMP packets. These packets can only be created via a socket of the SOCK_RAW type. Currently, Java only allows SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets. It seems unlikely that this will be added very soon, since many Unix versions only allow SOCK_RAW sockets to be created by root, and winsock does not address ICMP packets (win32 includes an unsupported and undocumented ICMP.DLL). For a full discussion of socket types, see Stevens' book (in the bibliography). 
    http://www.codeguru.com/java/articles/540.shtml
    -------------------------
    Author: Real Gagnon
    Author's WebSite: http://tactika.com/realhome/realhome.html 
    It's not possible to really "ping" a machine to check if it's alive or not (it's a long story, but to keep it short I will just say that the Socket class is not low-level enough for that operation). But we can emulate a ping by talking the "echo port". On a server, the echo port is always port 7. We write a string to that port and the server will echo the string.  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 = is.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();}
           }
          }