2012-10-09 173 views
7

我正在嘗試編寫一個函數,它將單個IP address作爲參數,並在本地網絡上查詢該機器的地址爲MAC address從本地網絡的IP地址獲取本機網絡上的機器MAC地址#

我見過很多例子,得到本地機器自己MAC address,但是沒有(我發現),似乎查詢本地網絡機器。

我知道這樣的任務是可以實現的,因爲這Wake on LAN scanner軟件掃描本地IP範圍和返回所有的機器的MAC地址/主機名。

誰能告訴我在哪裏,我開始試圖寫一個函數在C#來實現這一目標?任何幫助,將不勝感激。由於

編輯:

按照下面的Marco熔點的評論,已經使用ARP表。 arp class

+0

不知道它的工作原理,但有一個快速谷歌搜索,我發現這個庫,它應該做的伎倆:HTTP:// WWW。 tamirgal.com/blog/post/ARP-Resolver-C-Class.aspx](http://www.tamirgal.com/blog/post/ARP-Resolver-C-Class.aspx) –

+0

謝謝你,我相信我讀過ARP表是不一致的,並想知道是否有辦法爲MAC地址「ping」。 –

+1

我**認爲**如果您定期ping(或以其他方式嘗試聯繫)IP地址,則會導致ARP表刷新(否則網絡堆棧將無法首先與機器聯繫);當然這(如果有的話)只有當所需的機器在線時才起作用。我不認爲你可以得到離線IP地址的可靠結果,特別是如果你有動態分配的IP地址。 雖然我不是網絡專家,但我可能是錯的(試着和你一起思考問題)。 –

回答

0

根據上面的Marco Mp的評論,使用了ARP表。 arp class

+0

貴國的問題問的「獲取IP,並找到MAC地址」,並要求ARP代替RARP(MAC得到並返回你當前使用的IP /主機)。你最終在這裏結束了嗎? 2. 網站你指的是使用過程中的錯誤definiton(MAC到IP是RARP的替代ARP)... – Khan

13
public string GetMacAddress(string ipAddress) 
{ 
    string macAddress = string.Empty; 
    System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); 
    pProcess.StartInfo.FileName = "arp"; 
    pProcess.StartInfo.Arguments = "-a " + ipAddress; 
    pProcess.StartInfo.UseShellExecute = false; 
    pProcess.StartInfo.RedirectStandardOutput = true; 
     pProcess.StartInfo.CreateNoWindow = true; 
    pProcess.Start(); 
    string strOutput = pProcess.StandardOutput.ReadToEnd(); 
    string[] substrings = strOutput.Split('-'); 
    if (substrings.Length >= 8) 
    { 
     macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2)) 
       + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6] 
       + "-" + substrings[7] + "-" 
       + substrings[8].Substring(0, 2); 
     return macAddress; 
    } 

    else 
    { 
     return "not found"; 
    } 
} 

很晚編輯: 在開放的烴源項目ISPY(https://github.com/ispysoftware/iSpy),他們使用此代碼,這是一個更好一點

public static void RefreshARP() 
     { 
      _arpList = new Dictionary<string, string>(); 
      _arpList.Clear(); 
      try 
      { 
       var arpStream = ExecuteCommandLine("arp", "-a"); 
       // Consume first three lines 
       for (int i = 0; i < 3; i++) 
       { 
        arpStream.ReadLine(); 
       } 
       // Read entries 
       while (!arpStream.EndOfStream) 
       { 
        var line = arpStream.ReadLine(); 
        if (line != null) 
        { 
         line = line.Trim(); 
         while (line.Contains(" ")) 
         { 
          line = line.Replace(" ", " "); 
         } 
         var parts = line.Trim().Split(' '); 

         if (parts.Length == 3) 
         { 
          string ip = parts[0]; 
          string mac = parts[1]; 
          if (!_arpList.ContainsKey(ip)) 
           _arpList.Add(ip, mac); 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       Logger.LogExceptionToFile(ex, "ARP Table"); 
      } 
      if (_arpList.Count > 0) 
      { 
       foreach (var nd in List) 
       { 
        string mac; 
        ARPList.TryGetValue(nd.IPAddress.ToString(), out mac); 
        nd.MAC = mac;  
       } 
      } 
     } 

https://github.com/ispysoftware/iSpy/blob/master/Server/NetworkDeviceList.cs

更新2甚至更多晚了,但我認爲最好,因爲它使用正則表達式來更好地檢查完全匹配。

public string getMacByIp(string ip) 
{ 
    var macIpPairs = GetAllMacAddressesAndIppairs(); 
    int index = macIpPairs.FindIndex(x => x.IpAddress == ip); 
    if (index >= 0) 
    { 
     return macIpPairs[index].MacAddress.ToUpper(); 
    } 
    else 
    { 
     return null; 
    } 
} 

public List<MacIpPair> GetAllMacAddressesAndIppairs() 
{ 
    List<MacIpPair> mip = new List<MacIpPair>(); 
    System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); 
    pProcess.StartInfo.FileName = "arp"; 
    pProcess.StartInfo.Arguments = "-a "; 
    pProcess.StartInfo.UseShellExecute = false; 
    pProcess.StartInfo.RedirectStandardOutput = true; 
    pProcess.StartInfo.CreateNoWindow = true; 
    pProcess.Start(); 
    string cmdOutput = pProcess.StandardOutput.ReadToEnd(); 
    string pattern = @"(?<ip>([0-9]{1,3}\.?){4})\s*(?<mac>([a-f0-9]{2}-?){6})"; 

    foreach (Match m in Regex.Matches(cmdOutput, pattern, RegexOptions.IgnoreCase)) 
    { 
     mip.Add(new MacIpPair() 
     { 
      MacAddress = m.Groups["mac"].Value, 
      IpAddress = m.Groups["ip"].Value 
     }); 
    } 

    return mip; 
} 
public struct MacIpPair 
{ 
    public string MacAddress; 
    public string IpAddress; 
} 
+2

這是。對於後代替@Macro熔點答案.....爲什麼正確的答不是這個選擇作爲答案? – Khan

+0

爲什麼它不顯示自己的PC MAC,但發現其他所有? – Khan

+1

@Khan可能是因爲您不需要將自己的IP存儲在ARP表中,因爲您已經知道了您自己的IP和MAC –

0
using System.Net; 
using System.Runtime.InteropServices; 

[DllImport("iphlpapi.dll", ExactSpelling = true)] 
public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen); 

try 
{ 
    IPAddress hostIPAddress = IPAddress.Parse("XXX.XXX.XXX.XX"); 
    byte[] ab = new byte[6]; 
    int len = ab.Length, 
     r = SendARP((int)hostIPAddress.Address, 0, ab, ref len); 
    Console.WriteLine(BitConverter.ToString(ab, 0, 6)); 
} 
catch (Exception ex) { } 

或PC名稱

try 
     { 
      Tempaddr = System.Net.Dns.GetHostEntry("DESKTOP-xxxxxx"); 
     } 
     catch (Exception ex) { } 
     byte[] ab = new byte[6]; 
     int len = ab.Length, r = SendARP((int)Tempaddr.AddressList[1].Address, 0, ab, ref len); 
     Console.WriteLine(BitConverter.ToString(ab, 0, 6)); 
+0

你的代碼非常混亂。我從來沒有見過類似的東西!我認爲你必須澄清並整理你的代碼才能贏得一些聲譽。 –