Hi All!
I am developing WinPCap 3.1 wrapper in C# and I have a problem with
capturing packets with callback function.
Here is some code:
Declarations:
//C definition:
//typedef void(* pcap_handler)(u_char *user,
// const struct pcap_pkthdr *pkt_header,
// const u_char *pkt_data)
public delegate void DispatchDelegate (IntPtr user,
out IntPtr header,
IntPtr data);
//int pcap_dispatch ( pcap_t * p,
// int cnt,
// pcap_handler callback,
// u_char * user
// )
public static extern int pcap_dispatch(IntPtr handle,
UInt32 cnt,
[MarshalAs(UnmanagedType.FunctionPtr)]DispatchDelegate callback,
IntPtr user);
Code:
{
// Opening interface, etc...
m_Callback = new Wrapper.DispatchDelegate(ProcessPacket);
Wrapper.pcap_dispatch(handler, 100, m_Callback, IntPtr.Zero);
}
// Callback function:
public static void ProcessPacket (IntPtr user, IntPtr headerPointer,
IntPtr data)
{
pcap_pkthdr header = (pcap_pkthdr) Marshal.PtrToStructure
(headerPointer, typeof(pcap_pkthdr));
DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0);
date = date.AddSeconds(header.ts.tv_sec);
date = date.AddMilliseconds(header.ts.tv_usec / 1000);
Console.WriteLine("Time: {0}:{1}", header.ts.tv_sec,
header.ts.tv_usec);
Console.WriteLine("DateTime: " + date.ToString());
return;
}
And that is what's happening:
On the first call of the callback everything is OK.
On the second one, input data is not correct.
After the second call NullReferenceException appears and pcap_dispatch
ends.
BTW, capturing without callback works fine, so opening interfaces code
is OK.
Any ideas?
Regards,
Leszek