using System.Net.NetworkInformation
/// <summary>
/// 获取当前激活网络的MAC地址、IPv4地址、IPv6地址 - 方法2
/// </summary>
/// <param name="mac">网卡物理地址</param>
/// <param name="ipv4">IPv4地址</param>
public static void GetActiveIpAndMac2(out string mac, out
string ipv4, out string ipv6)
{
mac = "";
ipv4 = "";
ipv6 = "";
//需要引用:System.Net.NetworkInformation
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
if (allAddress.Count > 0)
{
if (adapter.OperationalStatus == OperationalStatus.Up)
{
mac = adapter.GetPhysicalAddress().ToString();
foreach (UnicastIPAddressInformation addr in allAddress)
{
if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipv4 = addr.Address.ToString();
}
if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
ipv6 = addr.Address.ToString();
}
}
if (string.IsNullOrWhiteSpace(mac) ||
(string.IsNullOrWhiteSpace(ipv4) && string.IsNullOrWhiteSpace(ipv6)))
{
mac = "";
ipv4 = "";
ipv6 = "";
continue;
}
else
{
if (mac.Length == 12)
{
mac = string.Format("{0}-{1}-{2}-{3}-{4}-{5}",
mac.Substring(0, 2), mac.Substring(2, 2), mac.Substring(4, 2),
mac.Substring(6, 2), mac.Substring(8, 2), mac.Substring(10, 2));
}
break;
}
}
}
}
}
获取当前激活网络的MAC地址、IPv4地址、IPv6地址 - 方法2<推荐>
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.