C# 获取windows当前ip地址与mac
时间: 2024-01-21 21:03:46 浏览: 81
可以使用以下代码获取Windows当前IP地址和MAC地址:
```csharp
using System.Net;
using System.Net.NetworkInformation;
using System.Linq;
public static string GetLocalIPAddress()
{
string ipAddress = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
break;
}
}
return ipAddress;
}
public static string GetMacAddress()
{
string macAddress = "";
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
macAddress = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray());
break;
}
}
return macAddress;
}
```
上述代码中,GetLocalIPAddress()函数将返回Windows当前使用的IPv4地址,而GetMacAddress()函数将返回Windows当前使用的MAC地址。请注意,如果存在多个活动网络适配器,则GetMacAddress()函数返回的是第一个不是环回适配器的MAC地址。
阅读全文