This article describes the method of obtaining MAC addresses in C#. It is a very common and practical function. The specific methods are as follows:
The main function codes are as follows:
/// <summary> /// Get the mac address according to the network card type/// </summary> /// <param name="networkType">Network card type</param>/// <param name="macAddressFormatHanlder">Format obtained mac address</param>/// <returns>The obtained mac address</returns>public static string GetMacAddress(NetworkInterfaceType networkType, Func<string, string> macAddressFormatHanlder) { string _mac = ; NetworkInterface[] _networkInterfaces = (); foreach (NetworkInterface adapter in _networkInterfaces) { if ( == networkType) { _mac = ().ToString(); if (!(_mac)) break; } } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; } /// <summary> /// Obtain the mac address according to the network card type and network card status/// </summary> /// <param name="networkType">Network card type</param>/// <param name="status">Network card status</param>///Up The network interface is running and can transmit data packets.///Down The network interface cannot transmit data packets.///Testing The network interface is running tests.///Unknown The status of the network interface is unknown.///Dormant The network interface is not in the state of transmitting packets; it is waiting for an external event.///NotPresent Due to missing components (usually hardware components), the network interface cannot transmit packets.///The LowerLayerDown network interface cannot transmit packets because it runs on one or more other interfaces, and at least one of these "lower layer" interfaces is closed./// <param name="macAddressFormatHanlder">Format obtained mac address</param>/// <returns>The obtained mac address</returns>public static string GetMacAddress(NetworkInterfaceType networkType, OperationalStatus status, Func<string, string> macAddressFormatHanlder) { string _mac = ; NetworkInterface[] _networkInterfaces = (); foreach (NetworkInterface adapter in _networkInterfaces) { if ( == networkType) { if ( != status) continue; _mac = ().ToString(); if (!(_mac)) break; } } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; } /// <summary> /// Get the first mac address you read/// </summary> /// <returns>The obtained mac address</returns>public static string GetMacAddress(Func<string, string> macAddressFormatHanlder) { string _mac = ; NetworkInterface[] _networkInterfaces = (); foreach (NetworkInterface adapter in _networkInterfaces) { _mac = ().ToString(); if (!(_mac)) break; } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; }
In some projects, for security reasons, you need to obtain the MAC address and then determine whether the MAC address is legal before you can log in. I hope the method summarized in this article will be helpful to everyone!