我使用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