有没有办法使用c#解析默认网关的mac地址?
使用
进行更新var x = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;
但我觉得我错过了什么。
答案 0 :(得分:3)
这样的事情对你有用,虽然你可能想要添加更多的错误检查:
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(uint destIP, uint srcIP, byte[] macAddress, ref uint macAddressLength);
public static byte[] GetMacAddress(IPAddress address)
{
byte[] mac = new byte[6];
uint len = (uint)mac.Length;
byte[] addressBytes = address.GetAddressBytes();
uint dest = ((uint)addressBytes[3] << 24)
+ ((uint)addressBytes[2] << 16)
+ ((uint)addressBytes[1] << 8)
+ ((uint)addressBytes[0]);
if (SendARP(dest, 0, mac, ref len) != 0)
{
throw new Exception("The ARP request failed.");
}
return mac;
}
答案 1 :(得分:3)
您真正想要的是执行地址解析协议(ARP)请求。 有很好的方法可以做到这一点。
WMI示例:
using System;
using System.Management;
namespace WMIGetMacAdr
{
class Program
{
static void Main(string[] args)
{
ManagementScope scope = new ManagementScope(@"\\localhost"); // TODO: remote computer (Windows WMI enabled computers only!)
//scope.Options = new ConnectionOptions() { Username = ... // use this to log on to another windows computer using a different l/p
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject obj in searcher.Get())
{
string macadr = obj["MACAddress"] as string;
string[] ips = obj["IPAddress"] as string[];
if (ips != null)
{
foreach (var ip in ips)
{
Console.WriteLine("IP address {0} has MAC address {1}", ip, macadr );
}
}
}
}
}
}
答案 2 :(得分:1)
您可能需要使用P / Invoke和一些本机Win API函数。
看看这个tutorial。