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

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

问题描述

,我想做以下等效:

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天全站免登陆