2010-01-25 80 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