C# 从C中的IP获取本地网络上的机器MAC地址#

C# 从C中的IP获取本地网络上的机器MAC地址#,c#,network-programming,ip,port,mac-address,C#,Network Programming,Ip,Port,Mac Address,我正在尝试编写一个函数,该函数将单个IP地址作为参数,并在本地网络上查询该机器的MAC地址 我看到过许多例子,它们获得了本地机器自己的MAC地址,但是(我发现)没有一个例子(我发现)能够查询本地网络机器的MAC地址 我知道这样的任务是可以实现的,因为这个软件扫描本地IP范围并返回所有机器上的MAC地址/主机名 谁能告诉我从哪里开始尝试用C#编写函数来实现这一点?任何帮助都将不胜感激。谢谢 编辑: 根据马可议员下面的评论,我们使用了ARP表。 根据Marco Mp的上述评论,我们使用了ARP表 非

我正在尝试编写一个函数,该函数将单个
IP地址
作为参数,并在本地网络上查询该机器的
MAC地址

我看到过许多例子,它们获得了本地机器自己的
MAC地址
,但是(我发现)没有一个例子(我发现)能够查询本地网络机器的MAC地址

我知道这样的任务是可以实现的,因为这个软件扫描本地IP范围并返回所有机器上的MAC地址/主机名

谁能告诉我从哪里开始尝试用C#编写函数来实现这一点?任何帮助都将不胜感激。谢谢

编辑:

根据马可议员下面的评论,我们使用了ARP表。

根据Marco Mp的上述评论,我们使用了ARP表

非常晚编辑: 在OpenSouce项目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;    
                }
            }
        }
publicstaticvoidrefresharp()
{
_arpList=新字典();
_arpList.Clear();
尝试
{
var arpStream=ExecuteCommandLine(“arp”、“-a”);
//消费前三行
对于(int i=0;i<3;i++)
{
arpStream.ReadLine();
}
//阅读条目
而(!arpStream.EndOfStream)
{
var line=arpStream.ReadLine();
如果(行!=null)
{
line=line.Trim();
while(第行包含(“”))
{
行=行。替换(“,”);
}
var parts=line.Trim().Split(“”);
如果(parts.Length==3)
{
字符串ip=部件[0];
字符串mac=部件[1];
如果(!\u arpList.ContainsKey(ip))
_arpList.Add(ip,mac);
}
}
}
}
捕获(例外情况除外)
{
Logger.LogExceptionToFile(例如,“ARP表”);
}
如果(_arpList.Count>0)
{
foreach(列表中的变量nd)
{
字符串mac;
TryGetValue(nd.IPAddress.ToString(),out mac);
nd.MAC=MAC;
}
}
}

更新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;
}
公共字符串getMacByIp(字符串ip)
{
var macIpPairs=getAllMacAddresssAndippairs();
int index=macIpPairs.FindIndex(x=>x.IpAddress==ip);
如果(索引>=0)
{
返回macIpPairs[index].MacAddress.ToUpper();
}
其他的
{
返回null;
}
}
公共列表GetAllMacAddresssandIPPairs()
{
List mip=新列表();
System.Diagnostics.Process pProcess=新的System.Diagnostics.Process();
pProcess.StartInfo.FileName=“arp”;
pProcess.StartInfo.Arguments=“-a”;
pProcess.StartInfo.UseShellExecute=false;
pProcess.StartInfo.RedirectStandardOutput=true;
pProcess.StartInfo.CreateNoWindow=true;
p进程开始();
字符串cmdOutput=pProcess.StandardOutput.ReadToEnd();
字符串模式=@“(?([0-9]{1,3}\.?){4})\s*(?([a-f0-9]{2}-?){6}”;
foreach(在Regex.Matches(cmdOutput、pattern、RegexOptions.IgnoreCase)中匹配m)
{
mip.Add(新的MacIpPair()
{
MacAddress=m.Groups[“mac”].值,
IpAddress=m.Groups[“ip”].值
});
}
返回mip;
}
公共结构MacIpPair
{
公共字符串地址;
公共字符串IP地址;
}
或使用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));

只是一个更好的执行版本的公认的方法

    public string GetMacByIp( string ip )
    {
        var pairs = this.GetMacIpPairs();

        foreach( var pair in pairs )
        {
            if( pair.IpAddress == ip )
                return pair.MacAddress;
        }

        throw new Exception( $"Can't retrieve mac address from ip: {ip}" );
    }

    public IEnumerable<MacIpPair> GetMacIpPairs()
    {
        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 ) )
        {
            yield return new MacIpPair()
            {
                MacAddress = m.Groups[ "mac" ].Value,
                IpAddress = m.Groups[ "ip" ].Value
            };
        }
    }

    public struct MacIpPair
    {
        public string MacAddress;
        public string IpAddress;
    }
公共字符串GetMacByIp(字符串ip)
{
var pairs=this.GetMacIpPairs();
foreach(成对变量对)
{
if(pair.IpAddress==ip)
返回pair.MacAddress;
}
抛出新异常($“无法从ip:{ip}检索mac地址”);
}
公共IEnumerable GetMacIpPairs()
{
System.Diagnostics.Process pProcess=新的System.Diagnostics.Process();
pProcess.StartInfo.FileName=“arp”;
pProcess.StartInfo.Arguments=“-a”;
pProcess.StartInfo.UseShellExecute=false;
pProcess.StartInfo.RedirectStandardOutput=true;
pProcess.StartInfo.CreateNoWindow=true;
p进程开始();
字符串cmdOutput=pProcess.StandardOutput.ReadToEnd();
字符串模式=@“(?([0-9]{1,3}\.?){4})\s*(?([a-f0-9]{2}-?){6}”;
foreach(在Regex.Matches(cmdOutput,pattern,RegexOptions.IgnoreCase)中匹配m)
{
新MacIpPair()的产量回报率
{
MacAddress=m.Groups[“mac”].值,
IpAddress=m.Groups[“ip”].值
};
}
}
公共结构MacIpPair
{
公共字符串地址;
公共字符串IP地址;
}

不确定它是否有效,但通过快速的谷歌搜索,我找到了这个库,它应该能起到作用:谢谢你,我相信我读到ARP表不一致,并且想知道是否有办法对MAC地址进行“ping”。我想如果你进行常规ping(或者尝试联系)它将导致ARP表刷新的IP地址(否则网络堆栈首先将无法联系机器);当然,只有当所需的机器在线时,这才会起作用。我认为脱机IP地址无法获得可靠的结果,特别是在动态分配IP的情况下。我不是一个网络专家,所以我可能是错的(试着和你一起思考这个问题)
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));
    public string GetMacByIp( string ip )
    {
        var pairs = this.GetMacIpPairs();

        foreach( var pair in pairs )
        {
            if( pair.IpAddress == ip )
                return pair.MacAddress;
        }

        throw new Exception( $"Can't retrieve mac address from ip: {ip}" );
    }

    public IEnumerable<MacIpPair> GetMacIpPairs()
    {
        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 ) )
        {
            yield return new MacIpPair()
            {
                MacAddress = m.Groups[ "mac" ].Value,
                IpAddress = m.Groups[ "ip" ].Value
            };
        }
    }

    public struct MacIpPair
    {
        public string MacAddress;
        public string IpAddress;
    }