【发布时间】:2020-03-28 23:33:10
【问题描述】:
现在我正在尝试在我的机器上的几个网络适配器中使用网络适配器,以便我可以获得网络适配器的 ip 地址、mac 地址和适配器名称。但我没有任何运气。 我找到的解决方案是Get current network adapter in use。 我不认为它适用于 .Net 框架项目,而是适用于 ASP.NET Core。
我的代码如下。
public void GetIpAndMacAddress()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
// Only consider Ethernet network interfaces
if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
nic.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties adapterProperties = nic.GetIPProperties();
foreach (var ip in adapterProperties.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
IPAddress = ip.Address.ToString();
}
string hexMac = nic.GetPhysicalAddress().ToString(),
regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})",
replace = "$1:$2:$3:$4:$5:$6";
IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();
netAdapterName = nic.Name;
MACAddress = Regex.Replace(hexMac, regex, replace);
return;
}
}
}
【问题讨论】:
-
“使用中”是什么意思?
-
@John_ReinstateMonica,感谢您的关注,这意味着我当前使用的网络适配器用于连接互联网。
标签: c# ip-address mac-address