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 Ping 

    public static void main(String[] args) throws java.io.IOException{ 
        NetworkInterface[] devices = JpcapCaptor.getDeviceList(); 
        //if(args.length<1){ 
            //System.out.println("Usage: java Ping "); 
         //   for(int i=0;i<args.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[1],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("172.80.3.47"),InetAddress.getByName("172.80.3.1")); 
         p.data="123".getBytes();          EthernetPacket ether=new EthernetPacket(); 
         ether.frametype=EthernetPacket.ETHERTYPE_IP; 
//填写自己和对方的mac地址,必须要正确填写,如果有错误将无法收到回包 
         ether.dst_mac=new byte[]{(byte)0x00,(byte)0xd0,(byte)0xf8,(byte)0xed,(byte)0x93,(byte)0xbe}; 
         ether.src_mac=new byte[]{(byte)0x00,(byte)0x13,(byte)0xd4,(byte)0xe1,(byte)0x56,(byte)0x5e}; 
         p.datalink=ether;          for(int i=0;i<10;i++)
         sender.sendPacket(p); 
        System.out.println("send..."); 
         ICMPPacket rp= null; 
        for(int i=0;i<10;i++){ 
             rp=(ICMPPacket)captor.getPacket(); 
            if(rp.src_ip.equals(InetAddress.getByName("172.80.3.1"))) 
              System.out.println(" rcv icmp echo reply"); 
            else 
            if (rp==null||!(rp.src_ip.equals(InetAddress.getByName("172.80.3.1"))))
                System.out.println("no rcv icmp echo reply"); 
               // return ; 
              
         } 
     } 

--------------------------
运行结果总是:
no rcv icmp echo reply
no rcv icmp echo reply
no rcv icmp echo reply
no rcv icmp echo reply
no rcv icmp echo reply
no rcv icmp echo reply
no rcv icmp echo reply
哪里出错了???

解决方案 »

  1.   

    我说的不明白吗?
    就是用jpcap发送ICMP包,然后收到回应就说明主机在线,收不到就说明不在线,类似于Ping程序(不考虑防火墙禁止Ping)
    现在dst_IP和dst_MAC都没错,而且主机在线,但是运行程序结果总是:
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    no rcv icmp echo reply 
    -------------------------
    不知道问题出在哪里了啊
      

  2.   

    在我这里运行是可以的,,第二次就能有回复信息,,估计是你的mac地址有错误,不知道你的是用什么方法得到的,,