C#获取本地计算机已启用的网卡名、IP和MAC(默认ipv4)
我将网卡名、Ip、Mac装在List里,例如:(一般工控机就只有一个本地连接,笔记本会有WLAN)
LNetworkInformation[0].Name; 就是网卡名
LNetworkInformation[0].Ip; 就是Ip
LNetworkInformation[0].Mac; 就是Mac
使用方法:
CsNetWorkParam NetWorkParameter = new CsNetWorkParam();
List<Network> LNetworkInformation = NetWorkParameter.GetNetworkInformation();
以NetworkInterface.GetAllNetworkInterfaces();为核心获取接口所有信息
功能类:
public class CsNetWorkParam
{
//使用方法:声明+调用
public struct Network
{
public string Name;
public string Mac;
public IPAddress Ip;
};
public List<Network> GetNetworkInformation()
{
//存储集合声明
List<Network> LNetwork = new List<Network>();
NetworkInterface[] InterfacesInformation = NetworkInterface.GetAllNetworkInterfaces();//获取网络接口所有信息 包含未启用的网卡
foreach (NetworkInterface networkInterface in InterfacesInformation)//遍历所有网络接口信息
{
bool bIsOpen = networkInterface.OperationalStatus == OperationalStatus.Up;//判断网络连接状态
bool bIsLoopback = networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback;//是否是 回环
//Loopback 回环127.0.0.1
//Wireless80211 无线网
//Ethernet 以太网
if (bIsOpen && !bIsLoopback)
{
//单个网卡声明
Network network = new Network();
//获取网卡名
network.Name = networkInterface.Name;
//获取ip
IPInterfaceProperties ipInterfaceProperties = networkInterface.GetIPProperties();//获取ip信息 包含ipv4和ipv6
foreach (UnicastIPAddressInformation ipAddressInformation in ipInterfaceProperties.UnicastAddresses)
{
if (ipAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)//判断是否符合ipv4
{
network.Ip = ipAddressInformation.Address;
}
}
//获取MAC
PhysicalAddress mac = networkInterface.GetPhysicalAddress();
string result = Regex.Replace(mac.ToString(), ".{2}", "$0:");//添加字符 .{插入位置} ${数组位置 默认0}{插入字符}
string strMac = result.Remove(result.Length - 1);
network.Mac = strMac;
LNetwork.Add(network);
}
}
return LNetwork;
}
}