Working in WinPcap, pcap_open does not always return a pointer
I'm working on a packet sniffer in C Sharp
using Winpcap, Here is the exact code:
[DllImport("wpcap.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr pcap_open(char[] devicename, int size, int mode, int timeout, ref IntPtr auth, ref IntPtr errbuf);
string devicename = "\\Device\\NPF_{EADB4C21-B0AF-4EF2-86AB-80A37F399D1C}";
IntPtr errbuf = IntPtr.Zero, auth = IntPtr.Zero, iface;
try
{
iface = pcap_open(devicename.ToCharArray(), 65536, 1, 1000, ref auth, ref errbuf);
}
catch (Exception er) { return; }
pcap_open does not always return a valid pointer to my network interface. Sometimes it returns NULL
(0). It used to show "PInvoke detected a Stack unbalance...", I corrected that by changing the calling convention. I even made sure that the char
used in devicename
is of 1 byte (charset ansi)
. Still something is going wrong.
Just an observation: Whenever I debug it, it always returns a 开发者_StackOverflowvalid pointer, but when I don't, it will return NULL
40% of the times.
I've checked everything in & out, googled a lot but could not figure out anything. What could be missing? The worst part is that I can't even catch the exception to handle it properly. Does anybody have an answer?
If pcap_open
returns 0, it means there was an error, and it would be written in errbuf
if it wasn't null.
Allocate some memory for it (at least PCAP_ERRBUF_SIZE which is 256 bytes), for example, with the method given in that answer then display the error string or try something like that (with string/StringBuilder):
[DllImport("wpcap.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr pcap_open(string devicename, int size, int mode, int timeout, IntPtr auth, StringBuilder errbuf);
string devicename = "\\Device\\NPF_{EADB4C21-B0AF-4EF2-86AB-80A37F399D1C}";
try
{
StringBuilder errbuf=new StringBuilder(256);
iface = pcap_open(devicename, 65536, 1, 1000, IntPtr.Zero, errbuf);
Console.WriteLine(errbuf.ToString());
}
catch (Exception er) { return; }
It may be that there's some sort of legit error. Have you tried setting iface to IntPtr.Zero and then checking ater you call pcap_open against IntPtr.Zero? If it's setting it to null, you should also be able to check for null as well.
WHen it's null, it looks like you will want to convert errorBuf to a string to see what the error message is.
精彩评论