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:
- import java.io.IOException;
- import java.util.Scanner;
- import jpcap. *;
- import jpcap.packet.*;
- publicclass NetFetcher implements PacketReceiver{
- @Override
- publicvoid receivePacket(Packet arg0) {
- // output the captured packets
- System.out.println(arg0);
- }
- publicstaticvoid main(String[] args){
- //Get the list of network card devices
- NetworkInterface[] devices = JpcapCaptor.getDeviceList();
- if(devices.length==0){
- System.out.println( "No network card information!" );
- return;
- }
- // output network card information
- for(int i=0;i<devices.length;i++){
- System.out.println("网卡"+i+"信息:"+devices[i].name);
- for(NetworkInterfaceAddress address:devices[i].addresses){
- System.out.print(address.address+" ");
- }
- System.out.println("\n");
- }
- Scanner scan = new Scanner(System.in);
- System.out.println( "Please select the serial number of the network card you want to monitor: " );
- int index = scan.nextInt();
- //Monitor the selected network card
- try {
- JpcapCaptor jpcapCaptor = JpcapCaptor.openDevice(devices[index], 2000, false, 20);
- jpcapCaptor.loopPacket (- 1 , new NetFetcher ());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace ();
- }
- }
- }