C# Get network adapter info.

现实中,我们的机器可以有多块网卡(network adapter),
每块网卡只能有一个MAC Address,
但一块网卡又可以绑定多个IP Address。

现本机安装有3块网卡(其中后两块是虚的假卡),
第一块(物理存在的真卡)绑定了三个IP地址,
具体情况如下:

MAC Address : 00:05:5D:72:B6:53
      IP Address : 192.168.0.47
      IP Address : 192.168.0.106
      IP Address : 192.168.0.220

MAC Address : 00:50:56:C0:00:01
      IP Address : 192.168.204.1

MAC Address : 00:50:56:C0:00:08
      IP Address : 192.168.74.1

下面的程序将获取以上内容:

using System;
using System.Management;//It is need import in addition.
using System.Collections;

namespace PublicBill.GetNetworkAdapter
{
    
class GetNetworkAdapter
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            NetworkAdapter[] networkAdapters 
= (new GetNetworkAdapter()).GetNetworkAdapters();
            
foreach(NetworkAdapter networkAdapter in networkAdapters)
            
{
                Console.WriteLine(
"MAC Address : " + networkAdapter.MAC);
                
foreach(string ips in networkAdapter.IP)
                
{
                    Console.WriteLine(
" IP Address : " + ips);
                }

                Console.WriteLine();
            }

        }


        
/// <summary>
        
/// Get network adapters.
        
/// </summary>
        
/// <returns>return Network Adapter array.</returns>

        public NetworkAdapter[] GetNetworkAdapters()
        
{
            ArrayList macs 
= new ArrayList();

            ManagementClass mc 
= new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc 
= mc.GetInstances();
            
foreach(ManagementObject mo in moc)
            
{
                
if(Convert.ToBoolean(mo["ipEnabled"]) == true)
                
{
                    
string mac = mo["MacAddress"].ToString();
                    
string[] ips = (string[])mo["IPAddress"];

                    NetworkAdapter networkAdapter 
= new NetworkAdapter();
                    networkAdapter.MAC 
= mac;
                    networkAdapter.IP 
= ips;

                    macs.Add(networkAdapter);
                }

            }

            
return (NetworkAdapter[])macs.ToArray(typeof(NetworkAdapter));
        }

    }


    
/// <summary>
    
/// Simulation a Network Adapter, 
    
/// each one contains one mac address 
    
/// and two or more ip address.
    
/// </summary>

    class NetworkAdapter
    
{
        
private string mac;
        
private string[] ip;

        
public string MAC
        
{
            
get return mac; }
            
set { mac = value; }
        }


        
public string[] IP
        
{
            
get return ip; }
            
set { ip = value; }
        }

    }

}


以下是程序运行后的结果:
 

有关“Win32_NetworkAdapterConfiguration”,请参照
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_networkadapterconfiguration.asp
原文地址:https://www.cnblogs.com/publicbill/p/250984.html