我需要一个ping 网络设备的JAVA程序 就象在dos 下ping 网络设备一样, 可以知道发了多少包,接受了多少包的程序. 我现在写了一个这样的程序 
package com; import java.io.BufferedReader; 
import java.io.InputStreamReader; 
class ICMP 

/** 
  * ping 的一种实现,调用操作系统的ping命令 
  */ 
public static int ping(String host) { 
  String system = (String) (System.getProperty("os.name")).toLowerCase(); 
  String command = ""; 
  if (system.indexOf("win") != -1) { 
  command += "ping -n 5 " + host;//可以设置ping 的次数 
  } else if (system.indexOf("linux") != -1) { 
  command += "ping -t 4 " + host; //ping 四次 
  } else { 
  command += "ping " + host; 
  } 
  int minTime = Integer.MAX_VALUE, curTime; 
  try { 
  Process process = Runtime.getRuntime().exec("ping " + host); 
  BufferedReader in = new BufferedReader(new InputStreamReader( 
    process.getInputStream())); 
  String line = null; 
  int count = 10, index; 
  //最多只读10行 
  while ((line = in.readLine()) != null && count-- != 0) { 
    line = line.toLowerCase(); 
    if ((index = line.indexOf("time")) != -1) { 
    byte[] buf = line.getBytes(); 
    int start = 0, end = buf.length, i, j; 
    for (i = index + 4; i < buf.length; i++) { 
      if (Character.isDigit((char) buf[i])) { 
      start = i; 
      break; 
      } 
    } 
    if (i == buf.length) 
      continue; 
    for (j = start; j < buf.length; j++) { 
      if (Character.isLetter((char) buf[j])) { 
      end = j; 
      break; 
      } 
    } 
    curTime = Integer.parseInt(new String(buf, start, end 
      - start)); 
    if (curTime < minTime) { 
      minTime = curTime; 
    } 
    } 
  } 
  } catch (Exception ex) { 
  return Integer.MAX_VALUE; 
  } 
  return minTime; 

public static void main(String args[]) { 
ICMP ic=new ICMP(); 
System.out.println(ic.ping("10.64.2.7")); 
} } 我想能否通过 in.readLine() 读取的信息的次数来判断到底接受几个包. 
但是 感觉好象接受的不对 , 不知道这种想法对不对,如果可行 哪位朋友可以帮忙调试一下 改一下 . 如果有其他方法 或者类 也行. 
希望可以把问题解决 .谢谢 也希望感兴趣的朋友可以从中学习到知识 呵呵.

解决方案 »

  1.   

    帮楼主格式化一下代码:import java.io.BufferedReader;
    import java.io.InputStreamReader;public class ICMP {
    /**
     * ping 的一种实现,调用操作系统的ping命令
     */
    public static int ping(String host) {
    String system = (String) (System.getProperty("os.name")).toLowerCase();
    String command = "";
    if (system.indexOf("win") != -1) {
    command += "ping -n 5 " + host;// 可以设置ping 的次数
    } else if (system.indexOf("linux") != -1) {
    command += "ping -t 4 " + host; // ping 四次
    } else {
    command += "ping " + host;
    }
    int minTime = Integer.MAX_VALUE, curTime;
    try {
    Process process = Runtime.getRuntime().exec("ping " + host);
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    int count = 10, index;
    // 最多只读10行
    while ((line = in.readLine()) != null && count-- != 0) {
    line = line.toLowerCase();
    if ((index = line.indexOf("time")) != -1) {
    byte[] buf = line.getBytes();
    int start = 0, end = buf.length, i, j;
    for (i = index + 4; i < buf.length; i++) {
    if (Character.isDigit((char) buf[i])) {
    start = i;
    break;
    }
    }
    if (i == buf.length)
    continue;
    for (j = start; j < buf.length; j++) {
    if (Character.isLetter((char) buf[j])) {
    end = j;
    break;
    }
    }
    curTime = Integer.parseInt(new String(buf, start, end - start));
    if (curTime < minTime) {
    minTime = curTime;
    }
    }
    }
    } catch (Exception ex) {
    return Integer.MAX_VALUE;
    }
    return minTime;
    } public static void main(String args[]) {
    ICMP ic = new ICMP();
    System.out.println(ic.ping("10.64.2.7"));
    }}
      

  2.   

    import java.io.*;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    import java.util.*;
    import java.util.regex.*;
    public class Ping {    // The default daytime port
        static int DAYTIME_PORT = 13;    // The port we'll actually use
        static int port = DAYTIME_PORT;
        // Representation of a ping target
        // 
        static class Target { InetSocketAddress address;
    SocketChannel channel;
    Exception failure;
    long connectStart;
    long connectFinish = 0;
    boolean shown = false; Target(String host) {
        try {
    address = new InetSocketAddress(InetAddress.getByName(host),
    port);
        } catch (IOException x) {
    failure = x;
        }
    } void show() {
        String result;
        if (connectFinish != 0)
    result = Long.toString(connectFinish - connectStart) + "ms";
        else if (failure != null)
    result = failure.toString();
        else
    result = "Timed out";
        System.out.println(address + " : " + result);
        shown = true;
    }    }
        // Thread for printing targets as they're heard from
        //
        static class Printer
    extends Thread
        {
    LinkedList pending = new LinkedList(); Printer() {
        setName("Printer");
        setDaemon(true);
    } void add(Target t) {
        synchronized (pending) {
    pending.add(t);
    pending.notify();
        }
    } public void run() {
        try {
    for (;;) {
        Target t = null;
        synchronized (pending) {
    while (pending.size() == 0)
        pending.wait();
    t = (Target)pending.removeFirst();
        }
        t.show();
    }
        } catch (InterruptedException x) {
    return;
        }
    }    }
        // Thread for connecting to all targets in parallel via a single selector
        // 
        static class Connector
    extends Thread
        {
    Selector sel;
    Printer printer; // List of pending targets.  We use this list because if we try to
    // register a channel with the selector while the connector thread is
    // blocked in the selector then we will block.
    //
    LinkedList pending = new LinkedList(); Connector(Printer pr) throws IOException {
        printer = pr;
        sel = Selector.open();
        setName("Connector");
    } // Initiate a connection sequence to the given target and add the
    // target to the pending-target list
    //
    void add(Target t) {
        SocketChannel sc = null;
        try { // Open the channel, set it to non-blocking, initiate connect
    sc = SocketChannel.open();
    sc.configureBlocking(false); boolean connected = sc.connect(t.address); // Record the time we started
    t.channel = sc;
    t.connectStart = System.currentTimeMillis(); if (connected) {
        t.connectFinish = t.connectStart;
        sc.close();
        printer.add(t);
    } else {
        // Add the new channel to the pending list
        synchronized (pending) {
            pending.add(t);
        }     // Nudge the selector so that it will process the pending list
        sel.wakeup();
    }
        } catch (IOException x) {
    if (sc != null) {
        try {
    sc.close();
        } catch (IOException xx) { }
    }
    t.failure = x;
    printer.add(t);
        }
    } // Process any targets in the pending list
    //
    void processPendingTargets() throws IOException {
        synchronized (pending) {
    while (pending.size() > 0) {
        Target t = (Target)pending.removeFirst();
        try { // Register the channel with the selector, indicating
    // interest in connection completion and attaching the
    // target object so that we can get the target back
    // after the key is added to the selector's
    // selected-key set
    t.channel.register(sel, SelectionKey.OP_CONNECT, t);     } catch (IOException x) { // Something went wrong, so close the channel and
    // record the failure
    t.channel.close();
    t.failure = x;
    printer.add(t);     } }
        }
    } // Process keys that have become selected
    //
    void processSelectedKeys() throws IOException {
        for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();) { // Retrieve the next key and remove it from the set
    SelectionKey sk = (SelectionKey)i.next();
    i.remove(); // Retrieve the target and the channel
    Target t = (Target)sk.attachment();
    SocketChannel sc = (SocketChannel)sk.channel(); // Attempt to complete the connection sequence
    try {
        if (sc.finishConnect()) {
    sk.cancel();
    t.connectFinish = System.currentTimeMillis();
    sc.close();
    printer.add(t);
        }
    } catch (IOException x) {
        sc.close();
        t.failure = x;
        printer.add(t);
    }
        }
    } volatile boolean shutdown = false; // Invoked by the main thread when it's time to shut down
    //
    void shutdown() {
        shutdown = true;
        sel.wakeup();
    } // Connector loop
    //
    public void run() {
        for (;;) {
    try {
        int n = sel.select();
        if (n > 0)
    processSelectedKeys();
        processPendingTargets();
        if (shutdown) {
    sel.close();
    return;
        }
    } catch (IOException x) {
        x.printStackTrace();
    }
        }
    }    }
        public static void main(String[] args)
    throws InterruptedException, IOException
        {
    if (args.length < 1) {
        System.err.println("Usage: java Ping [port] host...");
        return;
    }
    int firstArg = 0; // If the first argument is a string of digits then we take that
    // to be the port number to use
    if (Pattern.matches("[0-9]+", args[0])) {
        port = Integer.parseInt(args[0]);
        firstArg = 1;
    } // Create the threads and start them up
    Printer printer = new Printer();
    printer.start();
    Connector connector = new Connector(printer);
    connector.start(); // Create the targets and add them to the connector
    LinkedList targets = new LinkedList();
    for (int i = firstArg; i < args.length; i++) {
        Target t = new Target(args[i]);
        targets.add(t);
        connector.add(t);
    } // Wait for everything to finish
    Thread.sleep(2000);
    connector.shutdown();
    connector.join(); // Print status of targets that have not yet been shown
    for (Iterator i = targets.iterator(); i.hasNext();) {
        Target t = (Target)i.next();
        if (!t.shown)
    t.show();
    }    }}
      

  3.   

    读取的信息的次数来判断到底接受几个包是不行的
    windows系统的话,ping完之后不是会出来一个统计信息的嘛
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),分析这个就行
    其他系统如solaris
    ----192.168.10.194 PING Statistics----
    11 packets transmitted, 11 packets received, 0% packet loss
    或者就出来192.168.10.194 is alive不推荐直接使用ping命令来统计接收丢包,有个开源jpcap,你看下
      

  4.   

    那上面 Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),其他系统如solaris 
     
          11 packets transmitted, 11 packets received, 0% packet loss这些信息 程序 怎么能获得呢?
      

  5.   

    就是你上面的BufferedReader inProcess process = Runtime.getRuntime().exec("ping " + host);
          BufferedReader bufferedReder = new BufferedReader(new InputStreamReader(process.getInputStream()));
          String s1;
          while((s1 = bufferedReder.readLine()) != null){
            System.out.println(s1);
          }
      

  6.   

    我把那个 jpcap也贴上来 大家一起研究下 import java.net.InetAddress; import jpcap.JpcapCaptor; 
    import jpcap.JpcapSender; 
    import jpcap.NetworkInterface; 
    import jpcap.packet.EthernetPacket; 
    import jpcap.packet.ICMPPacket; 
    import jpcap.packet.IPPacket; class ICMP 

        public static void main(String[] args) throws java.io.IOException{ 
            NetworkInterface[] devices = JpcapCaptor.getDeviceList(); 
            if(args.length<1){ 
                System.out.println("Usage: java ICMP <device index (e.g., 0, 1..)>"); 
                for(int i=0;i<devices.length;i++) 
                    System.out.println(i+":"+devices[i].name+"("+devices[i].description+")"); 
                System.exit(0); 
            } 
            int index=Integer.parseInt(args[0]); 
    //开启网络设备 
            JpcapCaptor captor=JpcapCaptor.openDevice(devices[index],2000,false,3000); 
    //设置只过滤 icmp包 
            captor.setFilter("icmp",true); 
            JpcapSender sender=captor.getJpcapSenderInstance(); 
             
            ICMPPacket p=new ICMPPacket(); 
            p.type=ICMPPacket.ICMP_ECHO; 
            p.seq=(short)0x0005; 
            p.id=(short)0x0006; 
             
            p.setIPv4Parameter(0,false,false,false,0,false,false,false,0,1010101,100,IPPacket.IPPROTO_ICMP, 
                InetAddress.getByName("192.168.1.30"),InetAddress.getByName("192.168.1.1")); 
    //-----这里边的2 个IP 是自己的机器的IP 与所PING机器的IP, 还是所PING机器的IP与网观呢
            p.data="abcdefghijklmnopqrstuvwabcdehghi".getBytes();         EthernetPacket ether=new EthernetPacket(); 
            ether.frametype=EthernetPacket.ETHERTYPE_IP; 
    //填写自己和对方的mac地址,必须要正确填写,如果有错误将无法收到回包 
    //这段程序需要MAC码 我无法取得---- 能否有不用取mac码的>????
            ether.dst_mac=new byte[]{(byte)0x00,(byte)0x03,(byte)0x2d,(byte)0x02,(byte)0xd1,(byte)0x69}; 
            ether.src_mac=new byte[]{(byte)0x08,(byte)0x00,(byte)0x46,(byte)0xad,(byte)0x3c,(byte)0x12}; 
            p.datalink=ether;          
            sender.sendPacket(p); 
            System.out.println("send..."); 
            ICMPPacket rp= null; 
            while(true){ 
                rp=(ICMPPacket)captor.getPacket(); 
                if(rp==null){ 
                    throw new IllegalArgumentException("no rcv icmp echo reply"); 
                }else 
                { 
                    System.out.println("rcv icmp echo reply"); 
                    return ; 
                } 
            } 
        } 
    } 这是jacap 的程序  里面有2个疑问
    //-----这里边的2 个IP 是自己的机器的IP 与所PING机器的IP, 还是所PING机器的IP与网观呢
            p.data="abcdefghijklmnopqrstuvwabcdehghi".getBytes();         EthernetPacket ether=new EthernetPacket(); 
            ether.frametype=EthernetPacket.ETHERTYPE_IP; 
    //填写自己和对方的mac地址,必须要正确填写,如果有错误将无法收到回包 
    //这段程序需要MAC码 我无法取得---- 能否有不用取mac码的>????
            ether.dst_mac=new byte[]{(byte)0x00,(byte)0x03,(byte)0x2d,(byte)0x02,(byte)0xd1,(byte)0x69}; 
            ether.src_mac=new byte[]{(byte)0x08,(byte)0x00,(byte)0x46,(byte)0xad,(byte)0x3c,(byte)0x12}; 
      

  7.   

    package com;import java.io.BufferedReader;
    import java.io.InputStreamReader;public class ICMP {
        /**
         * ping 的一种实现,调用操作系统的ping命令
         */
        public static int ping(String host) {
            String system = (String) (System.getProperty("os.name")).toLowerCase();
            String command = "";
            if (system.indexOf("win") != -1) {
                command += "ping -n 5 " + host;// 可以设置ping 的次数
            } else if (system.indexOf("linux") != -1) {
                command += "ping -t 4 " + host; // ping 四次
            } else {
                command += "ping " + host;
            }
            int minTime = Integer.MAX_VALUE, curTime;
            try {
                Process process = Runtime.getRuntime().exec("ping " + host);
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));      
                String line = null;
                // 最多只读10行
                while ((line = in.readLine()) != null ) {
                    line = line.toLowerCase();
                    /*
                    if ((index = line.indexOf("time")) != -1) {
                        byte[] buf = line.getBytes();
                        int start = 0, end = buf.length, i, j;
                        for (i = index + 4; i < buf.length; i++) {
                            if (Character.isDigit((char) buf[i])) {
                                start = i;
                                break;
                            }
                        }
                        if (i == buf.length)
                            continue;
                        for (j = start; j < buf.length; j++) {
                            if (Character.isLetter((char) buf[j])) {
                                end = j;
                                break;
                            }
                        }
                        curTime = Integer.parseInt(new String(buf, start, end - start));
                        if (curTime < minTime) {
                            minTime = curTime;
                        }
                    }
                    */
                    System.out.println(line);
                }
            } catch (Exception ex) {
                return Integer.MAX_VALUE;
            }
            return minTime;
        }    public static void main(String args[]) {
            ICMP ic = new ICMP();
            System.out.println(ic.ping("10.64.2.7"));
        }}这是我改过的 运行后输出的信息为 pinging 10.64.2.7 with 32 bytes of data:reply from 10.64.2.7: bytes=32 time<1ms ttl=252reply from 10.64.2.7: bytes=32 time<1ms ttl=252reply from 10.64.2.7: bytes=32 time<1ms ttl=252reply from 10.64.2.7: bytes=32 time<1ms ttl=252ping statistics for 10.64.2.7:    packets: sent = 4, received = 4, lost = 0 (0% loss),approximate round trip times in milli-seconds:    minimum = 0ms, maximum = 0ms, average = 0ms请问 大虾门 有没 方法 可以将 直接取得 sent 和received 的 如果是这样的信息话  我想 要费好多事进行判断与截取了
      

  8.   

    对了 大家回复的话 最好可以去 J2EE/EJB/JMS 那个栏去 占个坐  那里面有100分  题目是
    << [向java2000_net提问] 关于java   ping程序统计icmp报文   __大家来共同研究,学习   与进步:)   >>那样我好给大家分  这里的有点少!!!hehe
      

  9.   

    基本实现方法:
    1. 利用操作系统的 ping 命令,再对输出进行分析。
    2. 直接利用 ping 使用的ICMP协议,自己发包分析。