2011-09-03 33 views
0

我使用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搜索了很多但找不出任何東西。有什麼可能會丟失? 最糟糕的部分是我甚至無法抓住例外來正確處理它。有人有答案嗎?

回答

1

如果pcap_open返回0,則表示存在錯誤,並且如果它不爲空,它將被寫入errbuf

分配用於它的一些存儲器(至少PCAP_ERRBUF_SIZE是256個字節),例如,用在that answer給出的方法則顯示錯誤串或嘗試類似的東西(與串/ 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; } 
+0

我做到了。它將屏幕上的垃圾字符拼湊起來。我會發布代碼 – Rushil

+0

'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

+0

@Rushil我爲你的字符編碼問題編輯了我的答案。根據winpcap的源代碼,似乎pcap_open甚至不檢查errbuf是否爲空,它只是假設它是有效的並且可以容納256個字符。 – alexisdm

0

這可能是有某種合法性錯誤。你有沒有嘗試將iface設置爲IntPtr.Zero,然後檢查你是否對IntPtr.Zero調用pcap_open?如果它設置爲null,那麼你也應該能夠檢查null。

當它爲空時,它看起來像你想要將errorBuf轉換爲字符串來查看錯誤消息是什麼。

+0

我試着用'if((int)iface == 0)檢查'return;'異常仍然無法捕獲。怪異 – Rushil

+0

^if條件在catch塊內,但控件根本沒有進入catch塊。 – Rushil