gpt4 book ai didi

c# - 如何使用 .Net Core 在 Linux 上从同一网络的远程计算机获取 mac 地址

转载 作者:太空狗 更新时间:2023-10-29 11:12:14 25 4
gpt4 key购买 nike

只要“服务器”或应用程序在 Windows 和 .NET Framework 中运行,我已经拥有可以识别网络中设备 Mac 地址的工具。
我正在使用:

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-Address 的方法是使用 NetworkInterface .NET 类(在 GetMyMacAddress(string ip) 方法中使用)。要尝试从本地网络上的另一台设备获取 Mac-Address 是使用 arp 命令。
要在 Windows 中调用它,我必须导入系统 dll:[DllImport ("iphlpapi.dll", ExactSpelling = true)]
它引用:public static external int SendARP(int DestIP, int SrcIP, byte [] pMacAddr, ref uint PhyAddrLen);
并在这里使用它:SendARP ((int) IP.Address, 0, macAddr, ref macAddrLen)

当我移植 .NET Core 应用程序以在 Linux 上的 Raspberry PI 3 上运行时,我想知道如何在 Linux 上执行相同的过程(这是在该系统上执行此操作的正确方法吗?)。

NetworkInterface 类也存在于 .NET Core 中,位于 System.Net.NetworkInformation 命名空间下。

但是我如何从另一台机器的 IP 获取 Mac 地址(在具有 .NET Core 的 Linux 上)?

最佳答案

基于 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 = $@"/c {cmd}",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}

在询问 mac-address 之前 Ping class 进行测试

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,只需将正则表达式模式更改为 (([a-f0-9]{2}-?){6}) 并更改 string retorno = Bash(arp); 到 string retorno = CMD(arp); 或使用有问题的方法。我正在 Raspberry Pi3 上使用它。

关于c# - 如何使用 .Net Core 在 Linux 上从同一网络的远程计算机获取 mac 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46976238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com