/// <summary> /// Pause the capturing. /// </summary> /// <param name="adapterIndex"></param> /// <returns></returns> public bool PauseCapture(List <uint> adapters) { uint errno; try { foreach (uint adapterIndex in adapters) { errno = NetmonAPI.NmPauseCapture(this.captureEngineHandle, adapterIndex); if (errno != 0) { throw new Exception(FormatErrMsg("NmPauseCapture() failed", errno)); } } return(true); } catch (Exception ex) { NetmonAPI.NmCloseHandle(this.captureEngineHandle); NetmonAPI.NmCloseHandle(this.captureFileHandle); this.captureEngineHandle = IntPtr.Zero; this.captureFileHandle = IntPtr.Zero; ErrorMsg += ex.ToString(); return(false); } }
public void Close() { if (_fileHandle != IntPtr.Zero) { NetmonAPI.NmCloseHandle(_fileHandle); } _fileHandle = IntPtr.Zero; }
/// <summary> /// Stops the capture and clean the capture engine handle. /// </summary> /// <param name="adapterIndex"></param> /// <returns></returns> public bool StopCapture(List <uint> adapters) { if (this.captureEngineHandle != IntPtr.Zero) { foreach (uint adapterIndex in adapters) { NetmonAPI.NmStopCapture(this.captureEngineHandle, adapterIndex); } NetmonAPI.NmCloseHandle(this.captureFileHandle); this.captureFileHandle = IntPtr.Zero; } return(true); }
public void Stop() { uint errno; errno = NetmonAPI.NmStopCapture(this.capEngine, 1); if (errno != 0) { Console.Write("Error Stopping Capture"); } NetmonAPI.NmCloseHandle(this.capEngine); this.capEngine = IntPtr.Zero; NetmonAPI.NmCloseHandle(this.capFile); this.capFile = IntPtr.Zero; }
public void Dispose() { if (this.Disposed == false) { this.Disposed = true; if (Disposing) { NetmonAPI.NmCloseHandle(this.captureEngineHandle); NetmonAPI.NmCloseHandle(this.captureFileHandle); } // Free the unmanaged resource ... this.captureEngineHandle = IntPtr.Zero; this.captureFileHandle = IntPtr.Zero; } }
/// <summary> /// Start the NMCapture engine to collect traffic data. The trace file handle must be provided. /// </summary> /// <param name="adapterIndex">index of the target adapter.</param> /// <returns></returns> public bool StartCapture(List <uint> adapters) { uint errno; try { foreach (uint adapterIndex in adapters) { //Configure Adapter for capturing errno = NetmonAPI.NmConfigAdapter( this.captureEngineHandle, adapterIndex, CaptureCb, this.captureFileHandle, NmCaptureCallbackExitMode.DiscardRemainFrames); if (errno != 0) { throw new Exception(FormatErrMsg("NmConfigAdapter() failed", errno)); } errno = NetmonAPI.NmStartCapture(this.captureEngineHandle, adapterIndex, NmCaptureMode.LocalOnly); if (errno != 0) { throw new Exception(FormatErrMsg("NmStartCapture() failed", errno)); } } return(true); } catch (Exception ex) { NetmonAPI.NmCloseHandle(this.captureEngineHandle); NetmonAPI.NmCloseHandle(this.captureFileHandle); this.captureEngineHandle = IntPtr.Zero; this.captureFileHandle = IntPtr.Zero; ErrorMsg += ex.ToString(); return(false); } }
public IntPtr CreateFrameParser() { IntPtr FrameParser = IntPtr.Zero; UInt32 ret = 0; IntPtr pCallerContext = IntPtr.Zero; IntPtr nplParser = IntPtr.Zero; // Use NULL to load default NPL set. ret = NetmonAPI.NmLoadNplParser(null, NmNplParserLoadingOption.NmAppendRegisteredNplSets, pParserCallback, pCallerContext, out nplParser); if (ret != ERROR_SUCCESS) { Console.WriteLine("Failed to load NPL Parser"); return(FrameParser); } IntPtr frameParserConfig = IntPtr.Zero; ret = NetmonAPI.NmCreateFrameParserConfiguration(nplParser, pParserCallback, pCallerContext, out frameParserConfig); if (ret != ERROR_SUCCESS) { Console.WriteLine("Failed to load frame parser configuration."); NetmonAPI.NmCloseHandle(nplParser);//release the handler return(FrameParser); } else //now start to add filter { ret = NetmonAPI.NmConfigReassembly(frameParserConfig, NmReassemblyConfigOption.None, true); if (ret != ERROR_SUCCESS) { Console.WriteLine("Failed to config reassembly."); return(FrameParser); } String pfilterString = _filterString; Console.WriteLine(pfilterString); ret = NetmonAPI.NmAddFilter(frameParserConfig, pfilterString, out ulfilterId); if (ret != ERROR_SUCCESS) { Console.WriteLine("error to create filter,info:" + ret.ToString()); NetmonAPI.NmCloseHandle(frameParserConfig); NetmonAPI.NmCloseHandle(nplParser); return(FrameParser); } //add the properties foreach (String propertyString in _properties) { Console.WriteLine("add property:" + propertyString); UInt32 ulpropertyId; ret = NetmonAPI.NmAddProperty(frameParserConfig, propertyString, out ulpropertyId); if (ret == ERROR_SUCCESS) { PropertyIdDict.Add(propertyString, ulpropertyId); } else { Console.WriteLine("error when add property:" + propertyString); } } //add fields foreach (String filedString in _fields) { Console.WriteLine("add field:" + filedString); UInt32 ulfieldId; ret = NetmonAPI.NmAddField(frameParserConfig, filedString, out ulfieldId); if (ret == ERROR_SUCCESS) { FieldIdDict.Add(filedString, ulfieldId); } else { Console.WriteLine("error when add field:" + filedString); } } ret = NetmonAPI.NmCreateFrameParser(frameParserConfig, out FrameParser, NmFrameParserOptimizeOption.ParserOptimizeNone); if (ret != ERROR_SUCCESS) { Console.WriteLine("failed to create frame parser, info:" + ret.ToString()); return(FrameParser); } } return(FrameParser); }
private void Run() { IntPtr rawFrame; UInt32 ret; int count = 0; if (ERROR_SUCCESS == NetmonAPI.NmOpenCaptureFile(_capfile, out rawFrame)) { UInt32 frameCount = 0; Filtering _nmfilter = new Filtering(_filterString, _Outproperties, _Outfields); myFrameParser = _nmfilter.CreateFrameParser(); ret = NetmonAPI.NmGetFrameCount(rawFrame, out frameCount);//get the count of the frames // Console.WriteLine("framecount:" + frameCount); for (UInt32 framenumber = 0; framenumber < frameCount; framenumber++)//for each frame, apply the filter { // Console.WriteLine("framenumber:" + framenumber); _currentframeNumber = (int)framenumber + 1; IntPtr OneRawframe; ret = NetmonAPI.NmGetFrame(rawFrame, framenumber, out OneRawframe); // if (ret == ERROR_SUCCESS) { IntPtr parsedFrame, insFrame; ret = NetmonAPI.NmParseFrame(myFrameParser, OneRawframe, framenumber, NmFrameParsingOption.None, out parsedFrame, out insFrame); if (ret == ERROR_SUCCESS) { //Console.WriteLine("start to"); bool Passed = false; ret = NetmonAPI.NmEvaluateFilter(parsedFrame, _nmfilter.ulfilterId, out Passed); if (ret == ERROR_SUCCESS && Passed == true) { //construct _getframeUnit.FieldIdDict = _nmfilter.FieldIdDict; _getframeUnit.PropertyIdDict = _nmfilter.PropertyIdDict; _getframeUnit.ParsedFrame = parsedFrame; _getframeUnit.RawFrame = OneRawframe; _getframeUnit.FrameParser = myFrameParser; _getframeUnit.FrameNumber = _currentframeNumber; _getframeUnit.Pids = _pids.ToList(); //Console.WriteLine(_currentframeNumber); _getFrameValue = new GetFrameValue(_getframeUnit, _currentframeNumber); if (_getFrameValue.frameUnit.propertyUnit.tcpPayloadLength > 0) { AllGetFrames.Add(_getFrameValue.frameUnit); count++; } } NetmonAPI.NmCloseHandle(parsedFrame); NetmonAPI.NmCloseHandle(insFrame); } else { Console.WriteLine("error parsing frame:" + ret); } NetmonAPI.NmCloseHandle(OneRawframe);//release the cuurent parsed frame } else { Console.WriteLine("error when get frame:" + ret.ToString()); return; } } } else { Console.WriteLine("open capture file failed!"); } NetmonAPI.NmCloseHandle(rawFrame); //NetmonAPI.NmApiClose(); }
public static void Main(string[] args) { // Load API try { initialized = Program.InitializeNMAPI(); } catch (BadImageFormatException) { Console.WriteLine("There was an error loading the NMAPI.\n\nPlease ensure you have the correct version installed for your platform."); } catch (DllNotFoundException) { Console.WriteLine("There was an error loading the NMAPI DLL.\n\nPlease ensure you have Network Monitor 3.3 installed or try rebooting."); } CommandLineArguments commandReader = new CommandLineArguments(); if (commandReader.ParseCommandLineArguments(args)) { if (commandReader.IsNoArguments) { Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } else if (commandReader.IsRequestingHelp) { Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } else if (initialized) { Console.WriteLine("Running Test Application with Arguments:"); Console.WriteLine("\tCapture File: " + commandReader.CaptureFileName); Console.WriteLine("\tDisplay Filter: " + commandReader.DisplayFilter); Console.WriteLine("\tConversation Filter: " + commandReader.ConversationFilter); Console.WriteLine("\tSelected Frames: " + commandReader.SelectedFramesString); Console.WriteLine(); bool loadedparserengine = false; // Configure Parser Engine uint errno; IntPtr hNplParser = IntPtr.Zero; IntPtr hFrameParserConfig = IntPtr.Zero; uint conversationFilterId = 0; uint displayFilterId = 0; IntPtr hFrameParser = IntPtr.Zero; // Only load the parsing engine if we have to if (!string.IsNullOrEmpty(commandReader.ConversationFilter) || !string.IsNullOrEmpty(commandReader.DisplayFilter)) { Console.WriteLine("Loading Parser Engine..."); // Passing in null for the path will use the default configuration as specified in the Netmon UI errno = NetmonAPI.NmLoadNplParser(null, NmNplParserLoadingOption.NmAppendRegisteredNplSets, pErrorCallBack, IntPtr.Zero, out hNplParser); if (errno == ERROR_SUCCESS) { // Configure Frame Parser errno = NetmonAPI.NmCreateFrameParserConfiguration(hNplParser, pErrorCallBack, IntPtr.Zero, out hFrameParserConfig); if (errno == ERROR_SUCCESS) { // Enable Conversations errno = NetmonAPI.NmConfigConversation(hFrameParserConfig, NmConversationConfigOption.None, true); if (errno == ERROR_SUCCESS) { // Add Filters if (!string.IsNullOrEmpty(commandReader.ConversationFilter)) { Console.WriteLine("Adding Conversation Filter..."); errno = NetmonAPI.NmAddFilter(hFrameParserConfig, commandReader.ConversationFilter, out conversationFilterId); } if (errno == ERROR_SUCCESS) { if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { Console.WriteLine("Adding Display Filter..."); errno = NetmonAPI.NmAddFilter(hFrameParserConfig, commandReader.DisplayFilter, out displayFilterId); } if (errno == ERROR_SUCCESS) { errno = NetmonAPI.NmCreateFrameParser(hFrameParserConfig, out hFrameParser, NmFrameParserOptimizeOption.ParserOptimizeNone); if (errno == ERROR_SUCCESS) { Console.WriteLine("Parser Engine Loaded Successfully!"); Console.WriteLine(); loadedparserengine = true; } else { Console.WriteLine("Parser Creation Error Number = " + errno); } } else { Console.WriteLine("Display Filter Creation Error Number = " + errno); } } else { Console.WriteLine("Conversation Filter Creation Error Number = " + errno); } } else { Console.WriteLine("Conversation Error Number = " + errno); } if (!loadedparserengine) { NetmonAPI.NmCloseHandle(hFrameParserConfig); } } else { Console.WriteLine("Parser Configuration Error Number = " + errno); } if (!loadedparserengine) { NetmonAPI.NmCloseHandle(hNplParser); } } else { Console.WriteLine("Error Loading NMAPI Parsing Engine Error Number = " + errno); } } // Wait for confirmation Console.WriteLine("Press any key to continue"); Console.ReadKey(true); // Let's open the capture file // Open Capture File IntPtr captureFile = IntPtr.Zero; errno = NetmonAPI.NmOpenCaptureFile(commandReader.CaptureFileName, out captureFile); if (errno == ERROR_SUCCESS) { // Retrieve the number of frames in this capture file uint frameCount; errno = NetmonAPI.NmGetFrameCount(captureFile, out frameCount); if (errno == ERROR_SUCCESS) { // Loop through capture file for (uint ulFrameNumber = 0; ulFrameNumber < frameCount; ulFrameNumber++) { // Get the Raw Frame data IntPtr hRawFrame = IntPtr.Zero; errno = NetmonAPI.NmGetFrame(captureFile, ulFrameNumber, out hRawFrame); if (errno != ERROR_SUCCESS) { Console.WriteLine("Error Retrieving Frame #" + (ulFrameNumber + 1) + " from file"); continue; } // Need to parse once to get similar results to the UI if (loadedparserengine) { // Parse Frame IntPtr phParsedFrame; IntPtr phInsertedRawFrame; errno = NetmonAPI.NmParseFrame(hFrameParser, hRawFrame, ulFrameNumber, NmFrameParsingOption.FieldDisplayStringRequired | NmFrameParsingOption.FieldFullNameRequired | NmFrameParsingOption.DataTypeNameRequired, out phParsedFrame, out phInsertedRawFrame); if (errno == ERROR_SUCCESS) { // Check against Filters if (!string.IsNullOrEmpty(commandReader.ConversationFilter)) { bool passed; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, conversationFilterId, out passed); if (errno == ERROR_SUCCESS) { if (passed) { if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { bool passed2; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, displayFilterId, out passed2); if (errno == ERROR_SUCCESS) { if (passed2) { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } else { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } } else if (!string.IsNullOrEmpty(commandReader.DisplayFilter)) { bool passed; errno = NetmonAPI.NmEvaluateFilter(phParsedFrame, displayFilterId, out passed); if (errno == ERROR_SUCCESS) { if (passed) { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } } } else { PrintParsedFrameInformation(phParsedFrame, ulFrameNumber, commandReader); } NetmonAPI.NmCloseHandle(phInsertedRawFrame); NetmonAPI.NmCloseHandle(phParsedFrame); } else { Console.WriteLine("Error Parsing Frame #" + (ulFrameNumber + 1) + " from file"); } } else { // Just print what I just deleted... uint pulLength; errno = NetmonAPI.NmGetRawFrameLength(hRawFrame, out pulLength); if (errno == ERROR_SUCCESS) { if (commandReader.IsSelected(ulFrameNumber)) { Console.WriteLine("Frame #" + (ulFrameNumber + 1) + " (Selected) Frame Length(bytes): " + pulLength); } else { Console.WriteLine("Frame #" + (ulFrameNumber + 1) + " Frame Length(bytes): " + pulLength); } } else { Console.WriteLine("Error Getting Frame Length for Frame #" + (ulFrameNumber + 1)); } } NetmonAPI.NmCloseHandle(hRawFrame); } } else { Console.WriteLine("Error Retrieving Capture File Length"); } // Close Capture File to Cleanup NetmonAPI.NmCloseHandle(captureFile); } else { Console.WriteLine("Could not open capture file: " + commandReader.CaptureFileName); Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } if (loadedparserengine) { NetmonAPI.NmCloseHandle(hFrameParser); NetmonAPI.NmCloseHandle(hFrameParserConfig); NetmonAPI.NmCloseHandle(hNplParser); } } } else { Console.WriteLine(commandReader.LastErrorMessage); Console.WriteLine(CommandLineArguments.GetUsage("ExpertExample")); } // Pause so we can see the results when launched from Network Monitor Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); if (initialized) { CloseNMAPI(); } }
public void Test() { bool isElevated; WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); Console.WriteLine($"Elevated permissions: {isElevated}"); capHandler = new CaptureCallbackDelegate(CapHandlerCallback); uint ret; IntPtr myCapEng; ret = NetmonAPI.NmOpenCaptureEngine(out myCapEng); if (ret != 0) { Console.WriteLine("Error {0}\n", ret); } else { uint AdptCount; ret = NetmonAPI.NmGetAdapterCount(myCapEng, out AdptCount); if (ret != 0) { NetmonAPI.NmCloseHandle(myCapEng); Console.WriteLine("Error {0}\n", ret); } else { // Creates a capture file which will store the last 10MB of traffic captured ret = NetmonAPI.NmCreateCaptureFile(this.filename, 10000000, NmCaptureFileFlag.WrapAround, out this.capFile, out this.size); if (ret != 0) { Console.Write("Error Creating File"); } Console.WriteLine($"Adapters avalable: {AdptCount}"); for (uint i = 0; i < AdptCount; i++) { ret = NetmonAPI.NmConfigAdapter(myCapEng, i, capHandler, IntPtr.Zero, NmCaptureCallbackExitMode.ReturnRemainFrames); if (ret != 0) { Console.WriteLine("Could not config {0}, error {1}", i, ret); } else { Console.WriteLine("Configured Adpt {0}", i); } ret = NetmonAPI.NmStartCapture(myCapEng, i, NmCaptureMode.Promiscuous); if (ret != 0) { Console.WriteLine("Could not Start Capture on {0}, error {1}", i, ret); } else { Console.WriteLine("Started Adpt {0}", i); } } System.Threading.Thread.Sleep(5000); for (uint i = 0; i < AdptCount; i++) { ret = NetmonAPI.NmConfigAdapter(myCapEng, i, capHandler, IntPtr.Zero, NmCaptureCallbackExitMode.ReturnRemainFrames); if (ret != 0) { Console.WriteLine("Could not config {0}, error {1}", i, ret); } else { Console.WriteLine("Configured Adpt {0}", i); } Console.WriteLine("Starting Adpt {0} again", i); ret = NetmonAPI.NmStartCapture(myCapEng, i, NmCaptureMode.Promiscuous); if (ret != 0) { Console.WriteLine("Could not Start Capture again on {0}, error {1}", i, ret); } else { Console.WriteLine("Started Adpt {0} again", i); } } for (uint i = 0; i < AdptCount; i++) { ret = NetmonAPI.NmStopCapture(myCapEng, i); if (ret != 0) { Console.WriteLine("Could not Stop Capture on {0}, error {1}", i, ret); } else { Console.WriteLine("Stopped Adpt {0}", i); } } } NetmonAPI.NmCloseHandle(myCapEng); } }
static void Main(string[] args) { // / / Initialize NetworkMonitor API NM_API_CONFIGURATION apiConfig = new NM_API_CONFIGURATION(); apiConfig.Size = (ushort)(System.Runtime.InteropServices.Marshal.SizeOf(apiConfig)); NetmonAPI.NmGetApiConfiguration(ref apiConfig); apiConfig.ThreadingMode = 0; NetmonAPI.NmApiInitialize(ref apiConfig); IntPtr nplPointer = IntPtr.Zero; NetmonAPI.NmLoadNplParser(null, NmNplParserLoadingOption.NmAppendRegisteredNplSets, pErrorCallBack, IntPtr.Zero, out nplPointer); // / / Initialize Frame parser IntPtr parserConfigPointer; NetmonAPI.NmCreateFrameParserConfiguration(nplPointer, pErrorCallBack, IntPtr.Zero, out parserConfigPointer); NetmonAPI.NmConfigConversation(parserConfigPointer, NmConversationConfigOption.None, true); IntPtr ParserPointer; NetmonAPI.NmCreateFrameParser(parserConfigPointer, out ParserPointer, NmFrameParserOptimizeOption.ParserOptimizeNone); // / / Parse capture file IntPtr captureFileHandle; NetmonAPI.NmOpenCaptureFile("auto.cap", out captureFileHandle); uint rawFrameCount; NetmonAPI.NmGetFrameCount(captureFileHandle, out rawFrameCount); uint frameNumber = 0; IntPtr rawFrame; NetmonAPI.NmGetFrame(captureFileHandle, frameNumber, out rawFrame); IntPtr parsedFrame; IntPtr insRawFrame; NetmonAPI.NmParseFrame(ParserPointer, rawFrame, frameNumber, NmFrameParsingOption.FieldDisplayStringRequired | NmFrameParsingOption.FieldFullNameRequired | NmFrameParsingOption.DataTypeNameRequired, out parsedFrame, out insRawFrame); uint fieldCount; NetmonAPI.NmGetFieldCount(parsedFrame, out fieldCount); uint BUFFER_SIZE = 1024; char[] name = new char[BUFFER_SIZE * 2]; unsafe { fixed(char *pstr = name) { NetmonAPI.NmGetFieldName(parsedFrame, 0, NmParsedFieldNames.NamePath, BUFFER_SIZE * 2, pstr); } } String fieldName = new String(name).Replace("\0", String.Empty); NetmonAPI.NmCloseHandle(captureFileHandle); }