【问题标题】:Working in WinPcap, pcap_open does not always return a pointer在 WinPcap 中工作,pcap_open 并不总是返回一个指针
【发布时间】:2011-09-03 01:13:48
【问题描述】:

我正在使用 Winpcap 在C Sharp 中进行数据包嗅探器,这是确切的代码:

[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)。还是有问题。

只是一个观察:每当我调试它时,它总是返回一个有效的指针,但当我不这样做时,它会返回 NULL 40% 的时间。

我已经检查了所有内容,用谷歌搜索了很多,但无法弄清楚任何事情。可能缺少什么? 最糟糕的是,我什至无法捕捉到异常来正确处理它。有人有答案吗?

【问题讨论】:

    标签: c# c++ stack-overflow winpcap


    【解决方案1】:

    如果pcap_open返回0,则表示有错误,如果不为null,则写入errbuf

    为其分配一些内存(至少 PCAP_ERRBUF_SIZE 为 256 字节),例如,使用that answer 中给出的方法,然后显示错误字符串或尝试类似的操作(使用 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; }
    

    【讨论】:

    • 我做到了。它在屏幕上到处都是垃圾字符..我会发布代码
    • errbuf = Marshal.AllocHGlobal(256); try { iface = pcap_open(devicename.ToCharArray(), 65536, 1, 1000, auth, errbuf); char[] buf = new char[256]; Marshal.Copy(errbuf, buf, 0, 256); for (int a = 0; a < 256; a++) Console.Write((char)buf[a] + " "); } catch (Exception er) { return; }
    • @Rushil 我为您的字符编码问题编辑了答案。而且根据winpcap的源代码,似乎pcap_open甚至不检查errbuf是否为空,它只是假设它是有效的并且可以容纳256个字符。
    • 我能够找出问题所在。它是设备名称的格式。
    【解决方案2】:

    可能存在某种合法错误。您是否尝试过将 iface 设置为 IntPtr.Zero,然后检查您调用 pcap_open 对 IntPtr.Zero 的操作?如果将其设置为 null,您也应该能够检查 null。

    当它为空时,您似乎需要将 errorBuf 转换为字符串以查看错误消息是什么。

    【讨论】:

    • 我尝试检查使用if ((int)iface == 0) return; 仍然无法捕获异常。奇怪
    • ^if 条件在 catch 块内,但控件根本没有进入 catch 块..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2011-04-06
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多