2013-06-10 16 views
12

프로세스 보내기/받기 바이트를 얻으려면 어떻게해야합니까? 선호하는 방법은 C#으로하고있다.프로세스 네트워크 사용량 검색

저는 이것을 많이 조사했는데 이것에 대한 간단한 해결책을 찾지 못했습니다. 일부 솔루션은 WinPCap을 시스템에 설치하고이 lib로 작업하도록 제안했습니다.

이 사람이 묻는 질문 : Need "Processes with Network Activity" functionality in managed code - Like resmon.exe does it 나는 lib의 오버 헤드를 원하지 않는다.

간단한 해결책이 있습니까? 실제로 Windows의 리소스 모니터에서 "네트워크 작업 프로세스"탭 아래에있는 정확한 데이터를 원합니다. enter image description here

Windows의 리소스 모니터에서이 정보를 얻는 방법은 무엇입니까? 예제가 있습니까?

Missing network sent/received 또한 여기에 언급 된 카운터 방법을 사용해 보았지만 성공하지 못했습니다. 모든 카운터가이 카운터 아래에 표시되지는 않습니다. 그리고 리소스 모니터가이 카운터를 사용하지 않고도이 정보를 얻는 방법에 대해 궁금합니다.

+1

당신이 성능 카운터에 답을 찾지 못했습니다 :

나는 내 프로세스의 네트워크 IO를 다시보고 최근이 같은 것을 썼다? http://www.codeproject.com/Articles/8590/An-Introduction-To-Performance-Counters – Yogee

+0

성능 카운터 방식으로 작업하려고했으나 성공하지 못했습니다. 추가 한 링크도 읽으십시오. –

+1

http://stackoverflow.com/questions/438240/monitor-a-processs-network-usage –

답변

2

PerformanceCounter을 사용할 수 있습니다. 예제 코드 :

//Define 
string pn = "MyProcessName.exe"; 
var readOpSec = new PerformanceCounter("Process","IO Read Operations/sec", pn); 
var writeOpSec = new PerformanceCounter("Process","IO Write Operations/sec", pn); 
var dataOpSec = new PerformanceCounter("Process","IO Data Operations/sec", pn); 
var readBytesSec = new PerformanceCounter("Process","IO Read Bytes/sec", pn); 
var writeByteSec = new PerformanceCounter("Process","IO Write Bytes/sec", pn); 
var dataBytesSec = new PerformanceCounter("Process","IO Data Bytes/sec", pn); 

var counters = new List<PerformanceCounter> 
       { 
       readOpSec, 
       writeOpSec, 
       dataOpSec, 
       readBytesSec, 
       writeByteSec, 
       dataBytesSec 
       }; 

// get current value 
foreach (PerformanceCounter counter in counters) 
{ 
    float rawValue = counter.NextValue(); 

    // display the value 
} 

그리고 이것은 네트워크 카드의 성능 카운터를 얻는 것입니다. 그것은 특정

string cn = "get connection string from WMI"; 

var networkBytesSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", cn); 
var networkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", cn); 
var networkBytesTotal = new PerformanceCounter("Network Interface", "Bytes Total/sec", cn); 

Counters.Add(networkBytesSent); 
Counters.Add(networkBytesReceived); 
Counters.Add(networkBytesTotal); 
+0

그러나 장치 I/O 작업없이 네트워크 활동 만 원합니다. IO 읽기 작업/초 - 프로세스가 읽기 I/O 작업을 실행하는 속도 (초당 사건 수)를 표시하며 파일, 네트워크 및 장치 I/O를 포함하여 프로세스에서 생성 된 모든 I/O 작업을 계산합니다. " –

+0

단일 프로세스와 관련된 순수한 네트워크 카드 IO를 수행하는 다른 방법은 없습니다 (타사 라이브러리에 의존하지 않는 한). 내가 한 것은 프로세스 IO 및 네트워크 카드 IO 모니터링입니다. 나중에는 프로세스에만 국한되지 않습니다. 즉, 프로세스와 관계없이 모든 IO 카운터를 수집합니다. 네트워크 카드 카운터를 표시하도록 코드를 편집합니다. – oleksii

+1

귀하의 솔루션에 감사드립니다. 그러나 그것은 이미 발견 한 솔루션 중 하나이며, 프로세스 목표를 달성하지 못합니다. 이는 프로세스 네트워크 사용만을 얻는 것입니다. Windows의 리소스 모니터에서이 정보를 얻는 것처럼 다른 방법을 찾고 있는데 ... –

2

리소스 모니터를 처리하지 않습니다 참고 ETW 사용 - 다행히도 마이크로 소프트는 사용하기 쉽게 만들기 위해 좋은 nuget .net wrapper을 만들었습니다.

using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 
using Microsoft.Diagnostics.Tracing.Parsers; 
using Microsoft.Diagnostics.Tracing.Session; 

namespace ProcessMonitoring 
{ 
    public sealed class NetworkPerformanceReporter : IDisposable 
    { 
     private DateTime m_EtwStartTime; 
     private TraceEventSession m_EtwSession; 

     private readonly Counters m_Counters = new Counters(); 

     private class Counters 
     { 
      public long Received; 
      public long Sent; 
     } 

     private NetworkPerformanceReporter() { } 

     public static NetworkPerformanceReporter Create() 
     { 
      var networkPerformancePresenter = new NetworkPerformanceReporter(); 
      networkPerformancePresenter.Initialise(); 
      return networkPerformancePresenter; 
     } 

     private void Initialise() 
     { 
      // Note that the ETW class blocks processing messages, so should be run on a different thread if you want the application to remain responsive. 
      Task.Run(() => StartEtwSession()); 
     } 

     private void StartEtwSession() 
     { 
      try 
      { 
       var processId = Process.GetCurrentProcess().Id; 
       ResetCounters(); 

       using (m_EtwSession = new TraceEventSession("MyKernelAndClrEventsSession")) 
       { 
        m_EtwSession.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP); 

        m_EtwSession.Source.Kernel.TcpIpRecv += data => 
        { 
         if (data.ProcessID == processId) 
         { 
          lock (m_Counters) 
          { 
           m_Counters.Received += data.size; 
          } 
         } 
        }; 

        m_EtwSession.Source.Kernel.TcpIpSend += data => 
        { 
         if (data.ProcessID == processId) 
         { 
          lock (m_Counters) 
          { 
           m_Counters.Sent += data.size; 
          } 
         } 
        }; 

        m_EtwSession.Source.Process(); 
       } 
      } 
      catch 
      { 
       ResetCounters(); // Stop reporting figures 
       // Probably should log the exception 
      } 
     } 

     public NetworkPerformanceData GetNetworkPerformanceData() 
     { 
      var timeDifferenceInSeconds = (DateTime.Now - m_EtwStartTime).TotalSeconds; 

      NetworkPerformanceData networkData; 

      lock (m_Counters) 
      { 
       networkData = new NetworkPerformanceData 
       { 
        BytesReceived = Convert.ToInt64(m_Counters.Received/timeDifferenceInSeconds), 
        BytesSent = Convert.ToInt64(m_Counters.Sent/timeDifferenceInSeconds) 
       }; 

      } 

      // Reset the counters to get a fresh reading for next time this is called. 
      ResetCounters(); 

      return networkData; 
     } 

     private void ResetCounters() 
     { 
      lock (m_Counters) 
      { 
       m_Counters.Sent = 0; 
       m_Counters.Received = 0; 
      } 
      m_EtwStartTime = DateTime.Now; 
     } 

     public void Dispose() 
     { 
      m_EtwSession?.Dispose(); 
     } 
    } 

    public sealed class NetworkPerformanceData 
    { 
     public long BytesReceived { get; set; } 
     public long BytesSent { get; set; } 
    } 
} 
+0

관리자 권한으로 실행해야합니까? 나는'EnableKernelProvider' 메소드에서'System.UnauthorizedAccessException' 예외를 얻고 있습니다. –

+0

예 관리 권한이 필요합니다. – Kram