Network card capture --2 (listen packets)

JAVA's Socket is mainly at the transport layer, while the network card mainly works at the data link layer, so JAVA needs the support of other packets to monitor data packets.

First download Winpcap and install it. Then download Jpcap, unzip it, and put jpcap.dll in the bin directory of the jdk installation path and the bin directory of the jre installation path. Then create a new project and import jpcap.jar into it.

The procedure for listening for packets is as follows:

[java]  view plain copy
 
  1. import java.io.IOException;  
  2. import  java.util.Scanner;  
  3. import  jpcap. *;  
  4. import jpcap.packet.*;  
  5. publicclass NetFetcher implements PacketReceiver{   
  6.   
  7.     @Override  
  8.     publicvoid receivePacket(Packet arg0) {   
  9.           
  10.         // output the captured packets  
  11.         System.out.println(arg0);  
  12.     }  
  13.       
  14.     publicstaticvoid main(String[] args){    
  15.           
  16.         //Get the list of network card devices  
  17.         NetworkInterface[] devices = JpcapCaptor.getDeviceList();  
  18.         if(devices.length==0){  
  19.               
  20.             System.out.println( "No network card information!" );  
  21.             return;  
  22.         }  
  23.         // output network card information  
  24.         for(int i=0;i<devices.length;i++){  
  25.               
  26.             System.out.println("网卡"+i+"信息:"+devices[i].name);  
  27.             for(NetworkInterfaceAddress address:devices[i].addresses){  
  28.                   
  29.                 System.out.print(address.address+" ");  
  30.             }  
  31.             System.out.println("\n");  
  32.         }  
  33.           
  34.         Scanner scan = new Scanner(System.in);  
  35.         System.out.println( "Please select the serial number of the network card you want to monitor: " );  
  36.         int index = scan.nextInt();  
  37.           
  38.         //Monitor the selected network card  
  39.         try {  
  40.             JpcapCaptor jpcapCaptor = JpcapCaptor.openDevice(devices[index], 2000false20);  
  41.             jpcapCaptor.loopPacket (- 1 new  NetFetcher ());  
  42.         } catch (IOException e) {  
  43.             // TODO Auto-generated catch block  
  44.             e.printStackTrace ();  
  45.         }  
  46.     }  
  47. }  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940133&siteId=291194637