有没有办法使用c#从默认网关解析mac地址?
更新我正在使用
var x = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;
但我觉得我错过了一些东西。
有没有办法使用c#从默认网关解析mac地址?
更新我正在使用
var x = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;
但我觉得我错过了一些东西。
像这样的东西应该适合你,虽然你可能想添加更多的错误检查:
[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;
}
您真正想要的是执行地址解析协议 (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 );
}
}
}
}
}
}
您可能需要使用 P/Invoke 和一些本机 Win API 函数。
看看这个教程。