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 関数を使用する必要があります。
このチュートリアルをご覧ください。