Use C # for specific process network traffic under Windows

Source: Internet
Author: User

Recently, the boss took a ship heavy industry project, need to do a naval software system component Evaluation project, the project has a sub-project needs to obtain a specific process of various system parameters, project use. NET platform. When obtaining various system parameters for a particular process, other such as process ID, process name, process private working set, process working set, process IO throughput, Process CPU usage can be obtained directly using the relevant APIs in. NET, such as using the PerformanceCounter object to get the process private working set, process working set, process IO throughput, etc. However, there is no way for the network upstream traffic and downstream traffic for a particular process to be used directly. NET API access, the Web also found a lot of information, learned that only through the use of a particular process to capture the port number of the process network traffic, the implementation of their own also want to use C # call WinPcap Library, but because the implementation is more complex, so the use of the method is discarded. Later on the internet to find a foreign use C # implementation of the WinPcap Library Sharppcap Library, so the use of Sharppcap library to achieve a specific process network traffic function. Preparation involves downloading the SHARPPCAP library to your computer, then referencing PacketDotNet.dll and SharpPcap.dll in your project, and then adding references:

using Sharppcap; using Packetdotnet;

The implementation is more complex, the following is a brief introduction to the core part of the implementation:

First define the Processperformanceinfo class, which is used to record process-related information, processperformanceinfo defined as follows

//classes that log specific process performance Information     Public classprocessperformanceinfo:idisposable { Public intProcessID {Get;Set; }//Process ID         Public stringProcessName {Get;Set; }//Process Name         Public floatPrivateworkingset {Get;Set; }//Private Working Set (KB)         Public floatWorkingSet {Get;Set; }//Working Set (KB)         Public floatCPUTime {Get;Set; }//CPU Utilization (%)         Public floatiootherbytes {Get;Set; }//bytes per second IO operation (without control operation) Read and write Data (KB)         Public intiootheroperations {Get;Set; }//IO operations per second (not including read-write) (number of)         Public Longnetsendbytes {Get;Set; }//bytes of data sent over the network         Public Longnetrecvbytes {Get;Set; }//Network received bytes of data         Public Longnettotalbytes {Get;Set; }//Total network data bytes         Publiclist<icapturedevice> dev =NewList<icapturedevice>(); /// <summary>        ///ways to implement IDisposable/// </summary>         Public voidDispose () {foreach(Icapturedevice DinchDev)                {d.stopcapture ();            D.close (); }        }    }

Defines an attribute procinfo for a processperformanceinfo type:

 Public Get set; }

First step: Get all port numbers used by the specified process

Because a process may use multiple port numbers, monitoring a process traffic must monitor all the port numbers used by the process, and you can execute the command Netstat-ano with CMD and analyze the results. The code is as follows:

//Process ID            intPID =Procinfo.processid; //list of port numbers used by the hosting processlist<int> ports =Newlist<int>(); #regionGets the corresponding port number for the specified processProcess Pro=NewProcess (); Pro. Startinfo.filename="Cmd.exe"; Pro. Startinfo.useshellexecute=false; Pro. Startinfo.redirectstandardinput=true; Pro. Startinfo.redirectstandardoutput=true; Pro. Startinfo.redirectstandarderror=true; Pro. Startinfo.createnowindow=true; Pro.            Start (); Pro. Standardinput.writeline ("Netstat-ano"); Pro. Standardinput.writeline ("Exit"); Regex Reg=NewRegex ("\\s+", regexoptions.compiled); stringline =NULL; Ports.            Clear ();  while(line = Pro.) Standardoutput.readline ())! =NULL) { line=Line .                Trim (); if(line. StartsWith ("TCP", StringComparison.OrdinalIgnoreCase)) { Line= Reg. Replace (Line,","); string[] arr = line. Split (','); if(arr[4] ==PID. ToString ()) {stringSoc = arr[1]; intpos = Soc. LastIndexOf (':'); intPot =int. Parse (Soc. Substring (pos +1)); Ports.                    ADD (pot); }                }                Else if(line. StartsWith ("UDP", StringComparison.OrdinalIgnoreCase)) { Line= Reg. Replace (Line,","); string[] arr = line. Split (','); if(arr[3] ==PID. ToString ()) {stringSoc = arr[1]; intpos = Soc. LastIndexOf (':'); intPot =int. Parse (Soc. Substring (pos +1)); Ports.                    ADD (pot); }}} pro.            Close (); #endregion

The port numbers obtained are stored in the ports.

Step two: Get the native IP address and the native network device (that is, the NIC)

//get the native IP addressipaddress[] Addrlist =Dns.gethostbyname (Dns.gethostname ()).            AddressList; stringIP = addrlist[0].            ToString (); //get the native network device            vardevices =capturedevicelist.instance; intCount =devices.            Count; if(Count <1) {Console.WriteLine ("No Device found on the This machine"); return; }

The third step: Start grasping the package, as for the use of the Sharppcap library, in the official introduction of a very detailed: http://www.codeproject.com/Articles/12458/ Sharppcap-a-packet-capture-framework-for-net

The implementation code is as follows:

// start grabbing the bag             for (int0; i < count; + +i)            {                for (int0; J < ports. Count; + +J)                {                    captureflowrecv (IP, ports[j], i);                    Captureflowsend (IP, ports[j], i);                }            }

The CAPTUREFLOWRECV and Captureflowsend functions are defined as follows:

 Public  voidCaptureflowsend (stringIpintPortid,intDeviceID) {Icapturedevice device=(Icapturedevice) capturedevicelist.new () [DeviceID]; Device. Onpacketarrival+=NewPacketarrivaleventhandler (device_onpacketarrivalsend); intReadtimeoutmilliseconds = +; Device.            Open (devicemode.promiscuous, readtimeoutmilliseconds); stringFilter ="SRC host"+ IP +"and Src Port"+Portid; Device. Filter=filter; Device.            Startcapture ();        PROCINFO.DEV.ADD (device); }         Public  voidCAPTUREFLOWRECV (stringIpintPortid,intDeviceID) {Icapturedevice device=capturedevicelist.new () [DeviceID]; Device. Onpacketarrival+=NewPacketarrivaleventhandler (DEVICE_ONPACKETARRIVALRECV); intReadtimeoutmilliseconds = +; Device.            Open (devicemode.promiscuous, readtimeoutmilliseconds); stringFilter ="DST host"+ IP +"and DST Port"+Portid; Device. Filter=filter; Device.            Startcapture ();        PROCINFO.DEV.ADD (device); }
Private void device_onpacketarrivalsend (object  sender, Captureeventargs e)        {            var len = e.packet.data.length;             + = len        ;        } Private void device_onpacketarrivalrecv (object  sender, Captureeventargs e)        {             var len = e.packet.data.length;             + = len;        }

Fourth step: Set refresh upstream downstream traffic per second

/// <summary>        ///Real-time Refresh performance Parameters/// </summary>         Public voidRefershinfo () {procinfo.netrecvbytes=0; Procinfo.netsendbytes=0; Procinfo.nettotalbytes=0; Thread.Sleep ( +); Procinfo.nettotalbytes= Procinfo.netrecvbytes +procinfo.netsendbytes; }

Fifth step: Test part of the code

 while(true) {Console.WriteLine ("proc Nettotalbytes:"+procinfo.nettotalbytes); Console.WriteLine ("proc Netsendbytes:"+procinfo.netsendbytes); Console.WriteLine ("proc Netrecvbytes:"+procinfo.netrecvbytes); //Refresh the performance parameters every 1s call to refresh functionRefershinfo (); }            //Finally, remember to call the Dispose method to stop the packet and close the deviceProc.dispose ();

The above is only the core part of the implementation of the Code, designed to provide ideas for the reader, the implementation also need to add a lot of interfaces and classes to implement. Finally attached to their own running after the

Use C # for specific process network traffic under Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.