C# 怎么获取当前活动的网络适配器名字

2024-12-05 06:15:24
推荐回答(2个)
回答1:

C# .NET 获取当前网络适配器信息(描述、名称、标识符、类型、速度、操作状态、MAC地址),代码如下:

using System.Net.NetworkInformation;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本地计算机上网络接口的对象
            Console.WriteLine("适配器个数:" + adapters.Length);
            Console.WriteLine();
            foreach (NetworkInterface adapter in adapters)
            {
                Console.WriteLine("描述:" + adapter.Description);
                Console.WriteLine("标识符:" + adapter.Id);
                Console.WriteLine("名称:" + adapter.Name);
                Console.WriteLine("类型:" + adapter.NetworkInterfaceType);
                Console.WriteLine("速度:" + adapter.Speed * 0.001 * 0.001 + "M");
                Console.WriteLine("操作状态:" + adapter.OperationalStatus);
                Console.WriteLine("MAC 地址:" + adapter.GetPhysicalAddress());
 
                // 格式化显示MAC地址                
                PhysicalAddress pa = adapter.GetPhysicalAddress();//获取适配器的媒体访问(MAC)地址
                byte[] bytes = pa.GetAddressBytes();//返回当前实例的地址
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {                    
                    sb.Append(bytes[i].ToString("X2"));//以十六进制格式化
                    if (i != bytes.Length - 1)
                    {
                        sb.Append("-");
                    }
                }
                Console.WriteLine("MAC 地址:" + sb);
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

回答2:

 System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();


            foreach (System.Net.NetworkInformation.NetworkInterface ni in interfaces)


            {


                if (ni.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)


                {


                    Console.WriteLine("当前正在连接的IP是:"+ni.Name);


                }


                else


                {


                     Console.WriteLine("当前IP"+ni.Name+"处于静止或者中断状态。");


                }


            }

ni.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up 就可以判断