如何通过.NET访问ARP协议信息?

时间:2009-07-18 22:36:26

标签: c# .net ip lan arp

我正在尝试弄清楚我们的局域网中哪些设备在线和离线。我见过许多程序在进行一种图形网络概述,提供局域网IP和MAC地址。我想知道是否以及如何从C#/ .NET中提取这些(ARP?)信息?

任何示例代码段/链接都将受到赞赏。

5 个答案:

答案 0 :(得分:33)

如果您知道哪些设备可以使用Ping Class。这将允许您至少填写ARP表。如果必须,您可以随时执行ARP -a并解析输出。这里还有一个链接,显示如何拨打电话GetIpNetTable。我在下面列出了Ping类的示例以及如何使用GetIpNetTable访问ARP表。

这是Ping Class

的示例
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace Examples.System.Net.NetworkInformation.PingTest
{
    public class PingExample
    {
        // args[0] can be an IPaddress or host name.
        public static void Main (string[] args)
        {
            Ping pingSender = new Ping ();
            PingOptions options = new PingOptions ();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            int timeout = 120;
            PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine ("Address: {0}", reply.Address.ToString ());
                Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
                Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
            }
        }
    }
}

这是GetIpNetTable的一个例子。

using System;
using System.Runtime.InteropServices;
using System.ComponentModel; 
using System.Net;

namespace GetIpNetTable
{
   class Program
   {
      // The max number of physical addresses.
      const int MAXLEN_PHYSADDR = 8;

      // Define the MIB_IPNETROW structure.
      [StructLayout(LayoutKind.Sequential)]
      struct MIB_IPNETROW
      {
         [MarshalAs(UnmanagedType.U4)]
         public int dwIndex;
         [MarshalAs(UnmanagedType.U4)]
         public int dwPhysAddrLen;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac0;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac1;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac2;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac3;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac4;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac5;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac6;
         [MarshalAs(UnmanagedType.U1)]
         public byte mac7;
         [MarshalAs(UnmanagedType.U4)]
         public int dwAddr;
         [MarshalAs(UnmanagedType.U4)]
         public int dwType;
      }

      // Declare the GetIpNetTable function.
      [DllImport("IpHlpApi.dll")]
      [return: MarshalAs(UnmanagedType.U4)]
      static extern int GetIpNetTable(
         IntPtr pIpNetTable,
         [MarshalAs(UnmanagedType.U4)]
         ref int pdwSize,
         bool bOrder);

      [DllImport("IpHlpApi.dll", SetLastError = true, CharSet = CharSet.Auto)]
      internal static extern int FreeMibTable(IntPtr plpNetTable);

      // The insufficient buffer error.
      const int ERROR_INSUFFICIENT_BUFFER = 122;

      static void Main(string[] args)
      {
         // The number of bytes needed.
         int bytesNeeded = 0;

         // The result from the API call.
         int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);

         // Call the function, expecting an insufficient buffer.
         if (result != ERROR_INSUFFICIENT_BUFFER)
         {
            // Throw an exception.
            throw new Win32Exception(result);
         }

         // Allocate the memory, do it in a try/finally block, to ensure
         // that it is released.
         IntPtr buffer = IntPtr.Zero;

         // Try/finally.
         try
         {
            // Allocate the memory.
            buffer = Marshal.AllocCoTaskMem(bytesNeeded);

            // Make the call again. If it did not succeed, then
            // raise an error.
            result = GetIpNetTable(buffer, ref bytesNeeded, false);

            // If the result is not 0 (no error), then throw an exception.
            if (result != 0)
            {
               // Throw an exception.
               throw new Win32Exception(result);
            }

            // Now we have the buffer, we have to marshal it. We can read
            // the first 4 bytes to get the length of the buffer.
            int entries = Marshal.ReadInt32(buffer);

            // Increment the memory pointer by the size of the int.
            IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
               Marshal.SizeOf(typeof(int)));

            // Allocate an array of entries.
            MIB_IPNETROW[] table = new MIB_IPNETROW[entries];

            // Cycle through the entries.
            for (int index = 0; index < entries; index++)
            {
               // Call PtrToStructure, getting the structure information.
               table[index] = (MIB_IPNETROW) Marshal.PtrToStructure(new
                  IntPtr(currentBuffer.ToInt64() + (index *
                  Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW));
            }

            for (int index = 0; index < entries; index++)
            {
               MIB_IPNETROW row = table[index];
               IPAddress ip=new IPAddress(BitConverter.GetBytes(row.dwAddr));
               Console.Write("IP:"+ip.ToString()+"\t\tMAC:");

               Console.Write( row.mac0.ToString("X2") + '-');
               Console.Write( row.mac1.ToString("X2") + '-');
               Console.Write( row.mac2.ToString("X2") + '-');
               Console.Write( row.mac3.ToString("X2") + '-');
               Console.Write( row.mac4.ToString("X2") + '-');
               Console.WriteLine( row.mac5.ToString("X2"));

            }
         }
         finally
         {
            // Release the memory.
            FreeMibTable(buffer);
         }
      }
   }
}

答案 1 :(得分:1)

希望您尝试从IP地址获取MAC地址,而不是相反。

这是一个男人的例子的链接:

ARP Resolver

我没试过,让我们知道它是如何运作的。

答案 2 :(得分:1)

就我而言,我想查看网络上的所有ARP广播流量,以检测在网络上广播冲突IP和MAC地址的设备。我发现“ arp -a”轮询实现导致过时的信息,这使得检测IP地址冲突特别具有挑战性。例如,有两个设备正在响应ARP请求,但是由于一个响应总是在稍后到达,因此它会将早期响应隐藏在“ arp -a”表中。

我使用SharpPcap创建了一个具有用于ARP流量的捕获过滤器的捕获服务。然后,我使用Packet.Net来解析ARP数据包。最后,我登录并在数据包进入时生成有关IP和MAC地址冲突的警报。

答案 3 :(得分:0)

我遇到了类似的问题,想要获得MAC地址(给定Asp.Net Core项目的IP地址)。我希望它也可以在Windows和Linux上工作。由于找不到易于使用的解决方案,我决定自己创建一个小型library called ArpLookupNuGet)。

它能够在Windows和Linux上将Mac分配给IP。在Windows上,它使用IpHlpApi.SendARP API。在Linux上,它从/proc/net/arp读取arp表。如果找不到ip,它将尝试对其执行ping操作(以阻止操作系统执行arp请求),然后再次查看arp缓存。此方法无需任何依赖项(托管或非托管),也无需启动进程并解析其stdout等。

Windows版本不是异步的,因为底层API并非如此。由于linux版本确实是异步的(用于arp缓存的异步文件io + corefx异步ping api),所以我决定还是提供一个异步api,并在Windows上返回完成的Task

它很容易使用。真实的用法示例是available here

答案 4 :(得分:-4)

Google搜索“fingbox”。好像你正在试图检测这些蠢货?

这是一个完全合法的入侵探测器设备,很高兴知道谁在使用你的wifi,在什么端口上运输。有时它也会显示MAC地址并且可以ping通。有很多其他功能。