如何使用 C# 获取 IP 地址的物理 (MAC) 地址? [英] How do I obtain the physical (MAC) address of an IP address using C#?

查看:55
本文介绍了如何使用 C# 获取 IP 地址的物理 (MAC) 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,我想做以下等效的操作:

From C#, I want to do the equivalent of the following:

arp -a |findstr 192.168.1.254

或者,答案可以调用 SendARP 函数并获取结果.

Alternatively, the answer could call the SendARP function and get the results.

这将允许我的应用程序执行一些其他需要 MAC 地址的处理.

This will allow my application to do some other processing that requires the MAC address.

推荐答案

SendARP P/Invoke 是这样的:

SendARP P/Invoke goes like this:

[DllImport("iphlpapi.dll", ExactSpelling=true)]
public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );

PInvoke.NET 有这个例子:

IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address

byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;

if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)
     throw new InvalidOperationException("SendARP failed.");

string[] str = new string[(int)macAddrLen];
for (int i=0; i<macAddrLen; i++)
     str[i] = macAddr[i].ToString("x2");

Console.WriteLine(string.Join(":", str));

这篇关于如何使用 C# 获取 IP 地址的物理 (MAC) 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆