예제 #1
0
        public static bool CompileFilter(IntPtr pcapHandle,
                                         string filterExpression,
                                         uint mask,
                                         out IntPtr bpfProgram,
                                         out string errorString)
        {
            errorString = null;

            //Alocate an unmanaged buffer
            bpfProgram = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.bpf_program)));

            //compile the expressions
            var result = LibPcapSafeNativeMethods.pcap_compile(pcapHandle,
                                                               bpfProgram,
                                                               filterExpression,
                                                               1,
                                                               mask);

            if (result < 0)
            {
                var err = GetLastError(pcapHandle);

                // free up the program memory
                Marshal.FreeHGlobal(bpfProgram);
                bpfProgram = IntPtr.Zero; // make sure not to pass out a valid pointer

                // set the error string
                errorString = err;

                return(false);
            }

            return(true);
        }
예제 #2
0
        public static BpfProgram TryCreate(PcapHandle pcapHandle, string filter, int optimize = 1, uint netmask = 0)
        {
            var bpfProgram = new BpfProgram();
            int result;

            // Compile the expressions
            if (ThreadSafeCompile)
            {
                result = LibPcapSafeNativeMethods.pcap_compile(pcapHandle,
                                                               bpfProgram,
                                                               filter,
                                                               optimize,
                                                               netmask);
            }
            else
            {
                lock (SyncCompile)
                {
                    result = LibPcapSafeNativeMethods.pcap_compile(pcapHandle,
                                                                   bpfProgram,
                                                                   filter,
                                                                   optimize,
                                                                   netmask);
                }
            }
            if (result < 0)
            {
                // Don't use Dispose since we don't want pcap_freecode to be called here
                Marshal.FreeHGlobal(bpfProgram.handle);
                bpfProgram.SetHandle(IntPtr.Zero);
                bpfProgram = null;
            }
            return(bpfProgram);
        }