Winpcap has been the de facto library in packet capture applications, but the problem is that it is only natively available for C++ and C.
This is an attempt to port some of the crucial Winpcap functions for the .NET environment. The demonstration project here is written in C#.
First of all, you need to install Winpcap and then extract the project zip file. Be sure to reference dotnetwinpcap.dll in the project if not already so.
- static ArrayList FindAllDevs()
Returns an ArrayList of Device objects, each describing an Ethernet interface on the system.
- bool Open(string source, int snaplen, int flags, int read_timeout)
Opens an Ethernet interface with source as the name of the interface obtained from a Device object, snaplen is the max number of bytes to be captured from each packet, flags=1 means promiscuous mode, read_timeout is the blocking time of ReadNext before it returns.
- PCAP_NEXT_EX_STATE ReadNext( out PacketHeader p, out byte packet_data)
Reads a next packet and return the packet details (size and timestamp) to object p, and packet raw data in packet_data (array of bytes).
- void StopDump()
Stops dumping of capture data to a file.
- bool StartDump(string filename)
Starts dumping of capture data to a file.
- bool SetMinToCopy(int size)
Sets the minimum number of bytes required to be received by the driver before OnReceivePacket fires. Lowering this can increase response time, but increases system calls which lowers program efficiency.
- bool SetKernelBuffer(int bytes)
Sets the number of bytes in the driver kernel buffer for packet capture. Increase this to avoid packet loss and improve performance. Default is 1 MB.
- void StartListen()
Starts listening for packets.
- void StopListen()
Stops listening for packets.
- void Close()
Stops all operations and releases all resources.
- bool SendPacket(byte rawdata)
Sends bytes contained in rawdata over the wire. The ethernet checksum will be automatically added prior to sending the packet. Returns true if send is successful, false otherwise.
- bool IsListening
true if the dotnetWinpcap object is listening, false otherwise.
- string LastError
Returns the last error encountered by the library, if any.
Once StartListen() is called, OnReceivePacket will start to fire on every packet encountered, until StopListen() is called, or Close() is called.Code:delegate void ReceivePacket (object sender, PacketHeader p, byte s); event ReceivePacket OnReceivePacket;
Delegate objects of the above signature may be attached to the OnReceivePacket event to receive notification and perform further processing, as demonstrated in the demo source code.
Author: Victor Tan