1

c# を使用してデフォルト ゲートウェイから MAC アドレスを解決する方法はありますか?

私が働いている更新

var x = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses; 

しかし、私は何かが欠けているように感じます。

4

3 に答える 3

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;
}
于 2010-01-25T22:33:35.427 に答える
3

本当に必要なのは、アドレス解決プロトコル (ARP) 要求を実行することです。これを行うには、良い方法とそうでない方法があります。

  • .NET フレームワークの既存のメソッドを使用する (存在するかどうかは疑問ですが)
  • 独自の ARP 要求メソッドを作成します (おそらく、探しているよりも多くの作業が必要になります)。
  • マネージド ライブラリを使用する (存在する場合)
  • 管理されていないライブラリを使用する (Kevin が提案する iphlpapi.dll など)
  • ネットワーク内のリモート Windows コンピュータの MAC アドレスを取得するためにリモートのみが必要であることがわかっている場合は、Windows Management Instrumentation (WMI) を使用できます。

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 );
                    }
                }
            }
        }
    }
}
于 2010-01-25T23:30:06.233 に答える
1

おそらく、P/Invoke といくつかのネイティブの Win API 関数を使用する必要があります。

このチュートリアルをご覧ください。

于 2010-01-25T21:31:25.937 に答える