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

后端 未结 4 1406
失恋的感觉
失恋的感觉 2020-12-05 20:03

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

arp -a |findstr 192.168.1.254

Alternatively, the answer could call the SendARP funct

4条回答
  •  无人及你
    2020-12-05 20:47

    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 has this example:

    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

提交回复
热议问题