从默认网关获取mac地址?

时间:2010-01-25 21:15:24

标签: c# mac-address gateway

有没有办法使用c#解析默认网关的mac地址?

使用

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

但我觉得我错过了什么。

3 个答案:

答案 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)请求。 有很好的方法可以做到这一点。

  • 在.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 );
                    }
                }
            }
        }
    }
}

答案 2 :(得分:1)

您可能需要使用P / Invoke和一些本机Win API函数。

看看这个tutorial