2017-10-27 4 views
2

「サーバー」または「サーバー」が存在する限り、ネットワーク上のデバイスのMac-Addressを識別できるツールが既にあります。アプリケーションはWindowsおよび.NET Frameworkで実行されています。私が使用している
.Net Coreを使用して、リモートコンピュータ、同じネットワーク、linuxでmac-addressを取得する方法

using System; 
using System.Net; 
using System.Net.NetworkInformation; 
using System.Net.Sockets; 
using System.Runtime.InteropServices; 
namespace Tools 
{ 
    /// <summary> 
    /// Ferramentas para rede local 
    /// </summary> 
    public static class NET 
    { 
     private static string _erro; 
     public static string ErrorMessage { get { return _erro; } } 
     [DllImport("iphlpapi.dll", ExactSpelling = true)] 
     public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen); 
     /// <summary> 
     /// Recupera o MAC Address de um equipamento na rede local baseado em seu IP 
     /// </summary> 
     /// <param name="ip">IP em formato string (Ex: 192.168.0.10)</param> 
     /// <returns>String com o MAC Address no formato XX-XX-XX-XX-XX</returns> 
     public static string TryGetMacAddress(string ip) 
     { 
      try 
      { 
       IPAddress IP = IPAddress.Parse(ip); 
       byte[] macAddr = new byte[6]; 
       uint macAddrLen = (uint)macAddr.Length; 
       if (SendARP((int)IP.Address, 0, macAddr, ref macAddrLen) != 0) 
       { 
        _erro = "Não foi possível executar comando ARP"; 
        return String.Empty; 
       } 
       string[] str = new string[(int)macAddrLen]; 
       for (int i = 0; i < macAddrLen; i++) 
        str[i] = macAddr[i].ToString("x2"); 
       return string.Join("-", str); 
      } 
      catch (Exception e) 
      { 
       _erro = e.Message; 
      } 
      return String.Empty; 
     } 
     /// <summary> 
     /// Dado um ip que pertença ao equipamento, o MAC Address será dado 
     /// </summary> 
     /// <param name="ip">IP que pertença ao equipamento</param> 
     /// <returns>string com os bytes separados por hífen</returns> 
     public static string GetMyMacAddress(string ip) 
     { 
      NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 
      foreach (NetworkInterface adapter in nics) 
      { 
       foreach (UnicastIPAddressInformation unip in adapter.GetIPProperties().UnicastAddresses) 
       { 
        if (unip.Address.AddressFamily == AddressFamily.InterNetwork) 
        { 
         if (unip.Address.ToString() == ip) 
         { 
          PhysicalAddress address = adapter.GetPhysicalAddress(); 
          return BitConverter.ToString(address.GetAddressBytes()); 
         } 
        } 
       } 
      } 
      return null; 
     } 
    } 
} 

をマシン自体からMACアドレスを取得する方法は、(GetMyMacAddress(string ip)方法での使用に)のNetworkInterface .NETクラスを使用することです。ローカルネットワーク上の別のデバイスからMac-Addressを取得しようとするには、arpコマンドを使用します。 public static external int SendARP(int DestIP, int SrcIP, byte [] pMacAddr, ref uint PhyAddrLen);
そして、ここでそれを使用する:[DllImport ("iphlpapi.dll", ExactSpelling = true)]
それは参照:SendARP ((int) IP.Address, 0, macAddr, ref macAddrLen)

私はラズベリー上で実行するために、.NETのコアアプリケーションを移植していたよう
は、私は、システムのDLLをインポートする必要がWindowsでそれを呼び出すにはLinux上でPI3を使用する場合、私はLinuxで同じプロセスを実行する方法を知りたい(このシステムでこれを行う正しい方法ですか?)。

NetworkInterfaceクラスは、.NETコアのSystem.Net.NetworkInformation名前空間の下にも存在します。

しかし、別のマシン(.NETコア搭載のLinux)のIPからMac-Addressを取得するにはどうすればよいですか?

答えて

2

https://pt.stackoverflow.com/a/250164/48585に基づいて、私はこのヘルパーを書いた:

using System.Diagnostics;  
///FOR LINUX 
     public static string Bash(string cmd) 
     { 
      var escapedArgs = cmd.Replace("\"", "\\\""); 

      var process = new Process() 
      { 
       StartInfo = new ProcessStartInfo 
       { 
        FileName = "/bin/bash", 
        Arguments = $"-c \"{escapedArgs}\"", 
        RedirectStandardOutput = true, 
        UseShellExecute = false, 
        CreateNoWindow = true, 
       } 
      }; 
      process.Start(); 
      string result = process.StandardOutput.ReadToEnd(); 
      process.WaitForExit(); 
      return result; 
     } 
    ///FOR WINDOWS 
    public static string CMD(string cmd) 
     { 
      var process = new Process() 
      { 
       StartInfo = new ProcessStartInfo 
       { 
        FileName = "cmd.exe", 
        Arguments = [email protected]"/c {cmd}", 
        RedirectStandardOutput = true, 
        UseShellExecute = false, 
        CreateNoWindow = true, 
       } 
      }; 
      process.Start(); 
      string result = process.StandardOutput.ReadToEnd(); 
      process.WaitForExit(); 
      return result; 
     } 

のPingクラスの前にテストが、私はこのツールを使用し、その後、MACアドレス

private static StringBuilder _erro = new StringBuilder(); 
public static string ErrorMessage { get { return _erro.ToString(); } } 
public static bool Ping(string ipOrName, int timeout = 0, bool throwExceptionOnError = false) 
     { 
      bool p = false; 
      try 
      { 
       using (Ping ping = new Ping()) //using System.Net.NetworkInformation; (.NET Core namespace) 
       { 
        PingReply reply = null; 
        if (timeout > 0) 
         reply = ping.Send(ipOrName, timeout); 
        else 
         reply = ping.Send(ipOrName); 
        if (reply != null) 
         p = (reply.Status == IPStatus.Success); 
        //p = Convert.ToInt32(reply.RoundtripTime); 
       } 
      } 
      catch (PingException e) 
      { 
       _erro.Append(e.Message); 
       _erro.Append(Environment.NewLine); 
       if (throwExceptionOnError) throw e; 
      } 
      catch (Exception ex) 
      { 
       _erro.Append(ex.Message); 
       _erro.Append(Environment.NewLine); 
      } 
      return p; 
     } 

を尋ねる作るために:

public static string TryGetMacAddressOnLinux(string ip) 
    { 
     _erro.Clear(); 
     if (!Ping(ip)) 
      _erro.Append("Não foi possível testar a conectividade (ping) com o ip informado.\n"); 
     string arp = $"arp -a {ip}"; 
     string retorno = Bash(arp); 
     StringBuilder sb = new StringBuilder(); 
     string pattern = @"(([a-f0-9]{2}:?){6})"; 
     int i = 0; 
     foreach (Match m in Regex.Matches(retorno, pattern, RegexOptions.IgnoreCase)) 
     { 
      if (i > 0) 
       sb.Append(";"); 
      sb.Append(m.ToString()); 
      i++; 
     } 
     return sb.ToString(); 
    } 

Windowsの場合、Regexパターンをに変更してくださいstring retorno = Bash(arp);to string retorno = CMD(arp);を変更するか、または上記の方法を使用してください。 私はそれをRaspberry Pi3のように使用しています。

関連する問題