2

我正在使用 jpcap 库捕获数据包并保存在 Mysql 数据库中。我想分别做这两个功能。我的程序捕获数据包并保存在数据库中,然后捕获另一个数据包并保存在数据库中。我想要的是一种方法捕获数据包,另一种方法保存在数据库中。保存数据包不会停止捕获以完成该过程。

    public class PacketSniffer {
    private static String[] devices;
    private static PacketCapture captor;
    private static Packet info;            
    private static final Scanner input = new Scanner(System.in);
    private static final String FILTER = "";
    private static final int PACKET_COUNT = -1;

    public PacketSniffer()
    {
       captor = new PacketCapture();
       int i;
       devices =  PacketCapture.lookupDevices();

       for(i=0; i<devices.length; i++)
       {
          System.out.println(i+": "+devices[i]); // +devices[i].name
          System.out.println();
       }
       String device = input.nextLine();
       captor.open(device, 65535, true, 0);
       captor.setFilter(FILTER, true);
       captor.addPacketListener(new PacketCapture());
       captor.capture(PACKET_COUNT);             
    }
}

处理捕获数据包的数据包处理程序:

    public class PacketHandler implements PacketListener {

    Queue<Packet> queue;

    @Override
    public void packetArrived(Packet packet) 
    {
       System.out.println(packet);
    } 

    public void savePacket()
    {
       //  Method to save packet in database 
    }
}
4

3 回答 3

0
public class PacketCapture implements PacketListener,Runnable {
Queue<Packet> queue = new LinkedList<>();
@Override
public void packetArrived(Packet packet) 
{
   queue.add(packet);
   System.out.println(m_counter++);
}

public void run()
{
  while(!(queue.equals(null))){
    System.out.println(queue.poll());
 }
 }
 }

在主要方法中

 public static void main(String[] args) {

     Thread t1 = new Thread(new PacketSniffer());
    Thread t2 = new Thread(new PacketCapture());
     t1.start();
    t2.start();
}
于 2014-04-28T11:17:30.613 回答
0

好吧,你可以在这里做的是让两个线程同时运行,一个用于数据包捕获,一个用于将数据包存储在数据库中。您可以使用任何消息传递库(如 zeroMQ 或 rabbitMQ)在收到数据包后立即将数据包异步发送到数据库线程,这将自动处理任何排队。这样,您的数据包捕获将不会被阻止,您将能够同时做这两件事。你唯一的瓶颈是你的数据库插入速度,如果你使用 nosql 或 mongodb 可以提高

于 2014-06-13T19:51:36.343 回答
0

现在他对这个例子有什么问题,它也没有在 Runnable1 类中显示值

 public class Test {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

 Thread t1 = new Thread(new Runnable1());
 t1.start();
  Thread t2 = new Thread(new RunnableDemo());
 t2.start();
}
}

 class RunnableDemo implements Runnable {
Queue queue = new LinkedList<>();
public void run() 
{
   queue.add(4);
    queue.add(8);
     queue.add(12);
   System.out.println("Running");
}

 }
 class Runnable1 implements Runnable {
public void run()
  {
    RunnableDemo RunnableDemo = new RunnableDemo();
    for(int i=0; i<=100; i++)
    {
    System.out.println(RunnableDemo.queue.poll());
    }

}
}

于 2014-04-28T13:31:03.427 回答