[C#/.NET] 取得網路介面相關資訊

在C#中如何取得網路介面相關資訊...

在C#中可以透過NetworkInterface這個類別的GetAllNetworkInterfaces方法來取得所有網路介面卡,接著再從個別網路卡的NetworkInterface得到IPInterfaceProperties以及PhysicalAddress兩個物件來分別取得IP和MAC的資訊。

 

請參考以下程式範例以及註解:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;

namespace Network
{
    class Program
    {
        static void ListNetworkInterfaceInfo() 
        {
            Console.WriteLine("{0,8:S}{1,18:S}{2,18:S}", "MAC", "IP", "Netmask");
            Console.WriteLine("===================================================");
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();   //取得所有網路介面類別(封裝本機網路資料)
            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet"))     
                {
                    //取得IPInterfaceProperties(可提供網路介面相關資訊)
                    IPInterfaceProperties ipProperties = adapter.GetIPProperties(); 
                    
                    if (ipProperties.UnicastAddresses.Count > 0)
                    {
                        PhysicalAddress mac = adapter.GetPhysicalAddress();                     //取得Mac Address
                        string name = adapter.Name;                                             //網路介面名稱
                        string description = adapter.Description;                               //網路介面描述
                        string ip = ipProperties.UnicastAddresses[0].Address.ToString();        //取得IP
                        string netmask = ipProperties.UnicastAddresses[0].IPv4Mask.ToString();  //取得遮罩

                        Console.WriteLine("{0,13:S}{1,18:S}{2,18:S}", mac, ip, netmask);   
                    }
                }
            }         
        }

        static void Main(string[] args)
        {
            ListNetworkInterfaceInfo();
            Console.WriteLine("請按任意鍵結束...");
            Console.ReadKey();
        }
    }
}


執行結果:

            MAC                          IP                      Netmask
===================================================
 00055D81ACCD     192.168.38.73       255.255.0.0
 485B39D07C3E        10.242.98.33     255.255.252.0
 08002700E00F     192.168.100.10     255.255.255.0
 005056C00001         172.16.232.1     255.255.255.0
 005056C00008         172.16.199.1     255.255.255.0
請按任意鍵結束...