2010-01-25 82 views
1

有没有办法解决使用C#的默认网关的Mac地址?从默认网关获取mac地址?

更新IM与

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

工作,但我觉得我失去了一些东西。

回答

1

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

看看这个tutorial

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; 
} 
3

你真正想要的是执行ADRESS解析协议(ARP)请求。 有很好或不太好的方法来做到这一点。

  • 在.NET框架使用现有方法(虽然我怀疑它的存在)
  • 写自己的ARP请求方法(不是你正在寻找可能更多的工作)
  • 使用管理库(如果存在的话)
  • 使用的非托管库(如IPHLPAPI.DLL由凯文的建议)
  • 如果你知道你只需要遥控器,让您的网络中的远程Windows计算机的MAC地址你可以使用Windows管理规范(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); 
        } 
       } 
      } 
     } 
    } 
} 
+1

+1一个不错的解释和良好的技术(只要网关运行的是Windows)。 – Kevin 2010-01-26 17:28:06