我使用Winpcap的工作的一个数据包嗅探器在C Sharp
,这是确切的代码:在WinPcap的工作,pcap_open并不总是返回一个指针
[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并不总是返回一个有效的指针我网络接口。有时它返回NULL
(0)。它用来显示“PInvoke检测到堆栈不平衡...”,我通过改变调用约定来纠正这一点。我甚至确保devicename
中使用的char
是1字节(charset ansi)
。仍然有问题。只是一个观察:每当我调试它,它总是返回一个有效的指针,但是当我不这样做时,它将返回40%的时间。
我已经检查了所有在& out,google搜索了很多但找不出任何东西。有什么可能会丢失? 最糟糕的部分是我甚至无法抓住例外来正确处理它。有人有答案吗?
我做到了。它将屏幕上的垃圾字符拼凑起来。我会发布代码 – Rushil
'errbuf = Marshal.AllocHGlobal(256); 尝试 iface = pcap_open(devicename.ToCharArray(),65536,1000,auth,errbuf); char [] buf = new char [256]; Marshal.Copy(errbuf,buf,0,256); (int a = 0; a <256; a ++) Console.Write((char)buf [a] +“”); } catch(Exception er){return; }' – Rushil
@Rushil我为你的字符编码问题编辑了我的答案。根据winpcap的源代码,似乎pcap_open甚至不检查errbuf是否为空,它只是假设它是有效的并且可以容纳256个字符。 – alexisdm