如何使用 C# 获取 IP 地址的物理 (MAC) 地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/187894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:13:52  来源:igfitidea点击:

How do I obtain the physical (MAC) address of an IP address using C#?

c#networking

提问by Iain

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

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

arp -a |findstr 192.168.1.254

Alternatively, the answer could call the SendARPfunction and get the results.

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

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

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

采纳答案by jop

SendARP P/Invoke goes like this:

SendARP P/Invoke 是这样的:

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

PInvoke.NEThas this example:

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));

回答by bugmagnet

Hook into the WMI subsystem. Some VBScript code to get going in the right direction is here

连接到 WMI 子系统。一些朝着正确方向前进的 VBScript 代码在这里

回答by Douglas Anderson

To find your own:

要找到自己的:

Add a reference to System.Management

添加对 System.Management 的引用

ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

ManagementObjectCollection mcCol = mc.GetInstances();

foreach (ManagementObject mcObj in mcCol)
{
  Console.WriteLine(mcObj["Caption"].ToString());
  Console.WriteLine(mcObj["MacAddress"].ToString());
}

Not sure about finding that of another device.

不确定找到另一台设备的那个。

回答by Dominic Jonas

Here is my solution.

这是我的解决方案。

public static class MacResolver
{
    /// <summary>
    /// Convert a string into Int32  
    /// </summary>
    [DllImport("Ws2_32.dll")]
    private static extern Int32 inet_addr(string ip);

    /// <summary>
    /// The main funtion 
    /// </summary> 
    [DllImport("Iphlpapi.dll")]
    private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 len);

    /// <summary>
    /// Returns the MACAddress by a string.
    /// </summary>
    public static Int64 GetRemoteMAC(string remoteIP)
    {   
        Int32 ldest = inet_addr(remoteIP);

        try
        {
            Int64 macinfo = 0;           
            Int32 len = 6;           

            int res = SendARP(ldest, 0, ref macinfo, ref len);

            return macinfo;    
        }
        catch (Exception e)
        {
            return 0;
        }
    }

    /// <summary>
    /// Format a long/Int64 into string.   
    /// </summary>
    public static string FormatMac(this Int64 mac, char separator)
    {
        if (mac <= 0)
            return "00-00-00-00-00-00";

        char[] oldmac = Convert.ToString(mac, 16).PadLeft(12, '0').ToCharArray();

        System.Text.StringBuilder newMac = new System.Text.StringBuilder(17);

        if (oldmac.Length < 12)
            return "00-00-00-00-00-00";

        newMac.Append(oldmac[10]);
        newMac.Append(oldmac[11]);
        newMac.Append(separator);
        newMac.Append(oldmac[8]);
        newMac.Append(oldmac[9]);
        newMac.Append(separator);
        newMac.Append(oldmac[6]);
        newMac.Append(oldmac[7]);
        newMac.Append(separator);
        newMac.Append(oldmac[4]);
        newMac.Append(oldmac[5]);
        newMac.Append(separator);
        newMac.Append(oldmac[2]);
        newMac.Append(oldmac[3]);
        newMac.Append(separator);
        newMac.Append(oldmac[0]);
        newMac.Append(oldmac[1]);

        return newMac.ToString();
    }
}