簡體   English   中英

從網絡捕獲數據包並使用jpcap庫保存在數據庫中

[英]capturing packets from network and saving in database using jpcap library

我正在使用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);             
    }
}

Packet Handler處理捕獲的數據包:

    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 
    }
}
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();
}

現在他對此軸問題有什么問題,它也沒有在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());
    }

}
}

好吧,在這里您可以做的是有兩個線程同時運行,一個線程用於捕獲數據包,另一個線程用於將數據包存儲在數據庫中。 您可以使用任何消息傳遞庫(例如zeroMQ或rabbitMQ)在接收到數據包后立即將其異步發送到數據庫線程,這將自動處理任何排隊。 這樣,您的數據包捕獲將不會被阻止,您將能夠同時完成這兩項操作。 唯一的瓶頸是數據庫插入速度,如果您使用nosql或mongodb,則可以提高數據庫插入速度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM