2011-05-12 4 views
4

인터넷에 연결된 네트워크 카드를 프로그래밍 방식으로 선택하려고합니다. 얼마나 많은 트래픽이 카드를 통해 진행되는지 모니터해야합니다. 이것은 내가 인스턴스 이름프로그래밍 방식으로 .NET에서 인터넷에 연결된 네트워크 카드를 선택하는 방법

var category = new PerformanceCounterCategory("Network Interface"); 
String[] instancenames = category.GetInstanceNames(); 

을 얻기 위해 사용하는 것입니다 그리고 이것은 내가 것,

[0] "6TO4 Adapter"  
[1] "Internal"  
[2] "isatap.{385049D5-5293-4E76-A072-9F7A15561418}"  
[3] "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller"  
[4] "isatap.{0CB9C3D2-0989-403A-B773-969229ED5074}"  
[5] "Local Area Connection - Virtual Network"  
[6] "Teredo Tunneling Pseudo-Interface" 

내가 솔루션은 강력하고 다른 PC에서 작동되고 싶은 내 컴퓨터에서 instancenames을 보는 방법 또한 .NET을 선호합니다. 나는 다른 해결책을 찾았지만, 그들은 다른 있나요 목적 netstat

  1. 사용 C++ or WMI
  2. 구문 분석 출력을 위해 더 복잡한 것 같다?

    감사합니다.

    이 질문에 먼저 읽고 난 이미 몇 가지 가능한 솔루션을 언급 한 것을 참조하십시오를 닫 투표하기 전에 편집

    . 좀 더 간단하고 강력한 기능이 있는지 묻습니다 (예 : C++, WMI 또는 구문 분석 콘솔 응용 프로그램 출력)

+0

가능한 중복 [인터넷에 연결되어있는 네트워크 어댑터를 확인하는 방법] (http://stackoverflow.com/questions/2172962/how-to-determine-which-network-adapter-is-connected -to-the-internet) –

+0

@Matt Ball 그것은 중복되지 않으며, 내 질문에 귀하의 링크를 언급했습니다 (다른 솔루션에서). 나는 .NET의 간단한 접근법을 찾고있다. – oleksii

답변

1

결국 WMI 및 외부 함수 호출을 사용하여 더 나은 해결책을 찾지 못했습니다. 만약 누군가가 관심이 있다면 여기에 내 코드가있다.

using System; 
using System.Collections.Generic; 
using System.Diagnostics.Contracts; 
using System.Linq; 
using System.Management; 
using System.Net; 
using System.Net.Sockets; 
using System.Runtime.InteropServices; 

using log4net; 

namespace Networking 
{ 
    internal class NetworkCardLocator 
    { 
     [DllImport("iphlpapi.dll", CharSet = CharSet.Auto)] 
     public static extern int GetBestInterface(UInt32 DestAddr, out UInt32 BestIfIndex); 

     private static ILog log = OperationLogger.Instance(); 

     /// <summary> 
     /// Selectes the name of the connection that is used to access internet or LAN 
     /// </summary> 
     /// <returns></returns> 
     internal static string GetConnectedCardName() 
     { 
      uint idx = GetConnectedCardIndex(); 
      string query = String.Format("SELECT * FROM Win32_NetworkAdapter WHERE InterfaceIndex={0}", idx); 
      var searcher = new ManagementObjectSearcher 
      { 
       Query = new ObjectQuery(query) 
      }; 

      try 
      { 
       ManagementObjectCollection adapterObjects = searcher.Get(); 

       var names = (from ManagementObject o in adapterObjects 
          select o["Name"]) 
          .Cast<string>() 
          .FirstOrDefault(); 

       return names; 
      } 
      catch (Exception ex) 
      { 
       log.Fatal(ex); 
       throw; 
      } 
     } 

     private static uint GetConnectedCardIndex() 
     { 
      try 
      { 
       string localhostName = Dns.GetHostName(); 
       IPHostEntry ipEntry = Dns.GetHostEntry(localhostName); 
       IPAddress[] addresses = ipEntry.AddressList; 
       var address = GetNeededIPAddress(addresses); 
       uint ipaddr = IPAddressToUInt32(address); 
       uint interfaceindex; 
       GetBestInterface(ipaddr, out interfaceindex); 

       return interfaceindex; 
      } 
      catch (Exception ex) 
      { 
       log.Fatal(ex); 
       throw; 
      } 
     } 

     private static uint IPAddressToUInt32(IPAddress address) 
     { 
      Contract.Requires<ArgumentNullException>(address != null); 

      try 
      { 
       byte[] byteArray1 = IPAddress.Parse(address.ToString()).GetAddressBytes(); 
       byte[] byteArray2 = IPAddress.Parse(address.ToString()).GetAddressBytes(); 
       byteArray1[0] = byteArray2[3]; 
       byteArray1[1] = byteArray2[2]; 
       byteArray1[2] = byteArray2[1]; 
       byteArray1[3] = byteArray2[0]; 
       return BitConverter.ToUInt32(byteArray1, 0); 
      } 
      catch (Exception ex) 
      { 
       log.Fatal(ex); 
       throw; 
      } 
     } 

     private static IPAddress GetNeededIPAddress(IEnumerable<IPAddress> addresses) 
     { 
      var query = from address in addresses 
         where address.AddressFamily == AddressFamily.InterNetwork 
         select address; 

      return query.FirstOrDefault(); 
     } 
    } 
} 
+0

WMI 대신'System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()'를 사용할 수 있습니다. 난'GetBestInterface'에 대한. NET 대체 모르겠지만. –

0
+0

답변 해 주셔서 감사합니다. 첫 번째 링크에서 그 사람이 자신의 카드 이름을 사용하기 때문에 이것은 정말로 귀찮은 것이 아닙니다. ** Realtek RTL8168B_8111B 제품군 PCI-E 기가비트 이더넷 NIC [NDIS 6.0] ** 및 두 번째 사람 : ** Intel [R] 82562V -2 10_100 네트워크 연결 **이 솔루션은 다른 하드웨어/소프트웨어 이름을 가질 수 있기 때문에 다른 PC에서 작동하지 않습니다. 나는 견고한 접근법을 찾고있다. – oleksii

관련 문제