Get a machines MAC address on the local network from its IP in C#

后端 未结 4 787
情深已故
情深已故 2020-12-09 05:34

I am trying write a function that takes a single IP address as a parameter and queries that machine on my local network for it\'s MAC address.

4条回答
  •  既然无缘
    2020-12-09 05:52

    using System.Net;
    using System.Runtime.InteropServices;
    
    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);
    
    try
    {
        IPAddress hostIPAddress = IPAddress.Parse("XXX.XXX.XXX.XX");
        byte[] ab = new byte[6];
        int len = ab.Length, 
            r = SendARP((int)hostIPAddress.Address, 0, ab, ref len);
        Console.WriteLine(BitConverter.ToString(ab, 0, 6));
    }
    catch (Exception ex) { }
    

    or with PC Name

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

提交回复
热议问题