如何在 .NET 中以编程方式选择连接到互联网的网卡

发布于 2024-11-07 04:51:03 字数 1086 浏览 2 评论 0原文

我想以编程方式选择连接到互联网的网卡。我需要它来监控通过该卡的流量。 这就是我用来获取实例名称的方法

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

这就是 instancenames 在我的机器上的外观

[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 上工作,我也更喜欢 .NET。我找到了其他解决方案,但它们的目的似乎更复杂

  1. 使用 C++ 或 WMI
  2. 解析 netstat

还有其他吗?

请注意,我已经提到了一些可用的解决方案。我问是否还有其他更简单、更强大的东西(即不是 C++、WMI 或解析控制台应用程序输出)

I want to programmatically select the network card that is connected to the Internet. I need this to monitor how much traffic is going through the card.
This is what I use to get the instance names

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

And this how instancenames looks on my machine

[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"

I want the solution to be robust and work on other PCs, I would also prefer .NET. I found other solutions, but they seem to be more complicated for the purpose

  1. Use C++ or WMI
  2. Parse output of netstat

Is there anything else?

See that I already mentioned some available solutions. I am asking if there is anything else, more simple and robust (i.e. NOT C++, WMI or parsing console application output)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦 2024-11-14 04:51:03

我最终使用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();
        }
    }
}

I end up useing WMI and external function call, didn't find any better solution. Here is my code if anybody is interested.

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();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文