/// <summary>/// 引入windowsAPI/// </summary>public class LibArp{//用于转换ip地址  [DllImport("ws2_32.dll")]public static extern int inet_addr(string cp);//用于发送APR包(根据APR协议!)  [DllImport("IPHLPAPI.dll")]public static extern int SendARP(int DestIP, int ScrIP, ref long pMacAddr, ref int PhyAddrLen);}/// <summary>/// 根据ARP映射获取指定IP的MAC地址/// </summary>/// <param name="IP"></param>/// <returns></returns>public string GetMACAddressByIP(string IP){StringBuilder MacRouteBuilder = new StringBuilder();string macRoute;try{int ldest = LibArp.inet_addr(IP); //将IP地址从 点数格式转换成无符号长整型  long macinfo = new long();int len = 6;//SendARP函数发送一个地址解析协议(ARP)请求获得指定的目的地IPv4地址相对应的物理地址  LibArp.SendARP(ldest, 0, ref macinfo, ref len);string TmpMac = Convert.ToString(macinfo, 16).PadLeft(12, '0');//转换成16进制  //  for (int i = 10; i >= 0; i = i - 2)//反过来读取,原因可以查看接口函数sendApr!  {MacRouteBuilder.Append(TmpMac.Substring(i, 2).ToUpper());if (i >= 2){MacRouteBuilder.Append("-");}}}catch (Exception Mye){MacRouteBuilder.Append("获取远程主机的MAC错误:");MacRouteBuilder.Append(Mye.ToString());}macRoute = MacRouteBuilder.ToString();return macRoute;}/// <summary>/// 获取ARP查询字符串/// </summary>/// <returns></returns>private static string GetARPResult(){Process p = null;string output = string.Empty;try{p = Process.Start(new ProcessStartInfo("arp", "-a"){CreateNoWindow = true,UseShellExecute = false,RedirectStandardOutput = true});output = p.StandardOutput.ReadToEnd();}catch (Exception ex){throw new Exception("IPInfo: Error Retrieving 'arp -a' Results", ex);}finally{if (p != null){p.Close();}}return output;}/// <summary>/// 获取IP地址与Mac地址对应数据表/// </summary>/// <returns>Mac-IP</returns>public static List<string[]> GetIPInfo(){try{var list = new List<string[]>();var ArpResult = GetARPResult();foreach (var arp in ArpResult.Split(new char[] { '\n', '\r' })){if (!string.IsNullOrEmpty(arp)){var OArp = arp.Split(new char[] { ' ', '\t' });var pieces = (from piece in OArpwhere !string.IsNullOrEmpty(piece)select piece).ToArray();if (pieces.Length == 3){//pieces[1]Mac//pieces[0]IPlist.Add(new string[2] { pieces[1], pieces[0] });}}}return list;}catch (Exception ex){throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex);}}

这是 获取局域网 所有主机 arp 映射

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Net;namespace PreviewDemo
{public class GetIPNetTable{// 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;/// <summary>/// 获取/// </summary>public static List<ArpIP> Get_IPNetTable(){List<ArpIP> ArrArpIP = new List<ArpIP>();// 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(newIntPtr(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"));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac0.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac1.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac2.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac3.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac4.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac5.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac6.ToString("X2")));ArrArpIP.Add(new ArpIP(ip.ToString(), row.mac7.ToString("X2")));}}finally{// Release the memory.FreeMibTable(buffer);}return ArrArpIP;}public class ArpIP{public ArpIP(string _IPAddress, string _MacAddress){IPAddress = _IPAddress;MacAddress = _MacAddress;}public string IPAddress { get; set; }public string MacAddress { get; set; }}}
}

C# 获取 ARP 映射相关推荐

  1. java 获取arp表,java – Android arp表 – 开发问题

    我正在编写的Android应用程序有两个问题. 我正在从/ proc / net / arp中读出本地arp表,并在哈希映射中保存ip和相应的mac地址.看我的功能.它运作正常. /** * Extr ...

  2. openwrt利用arp获取局域网设备IP

    openwrt利用arp获取局域网设备IP 文章目录 openwrt利用arp获取局域网设备IP 1. 前言 2. ARP概念 3. arp局域网搜索设备实现思路和代码 1. 前言 目前我们通过arp ...

  3. [图解]ARP协议(一)

    一.ARP概述 如果要在TCP/IP协议栈中选择一个"最不安全的协议",那么我会毫不犹豫把票投给ARP协议.我们经常听到的这些术语,包括"网络扫描"." ...

  4. 如何用ARP欺骗来嗅探主机流量

    如何用ARP欺骗来嗅探主机流量 发现这个是第四节的,囧,改改名字~ ARP攻击,其实原理非常简单. 根据局域网内地址寻址的弱点,我们伪造一个错误地址映射的ARP包,就可以诱导被攻击者将数据包先发送给攻 ...

  5. 如何对Windows Server 2008上的ARP缓存进行管理

    在今天的文章中,我们将探讨一下如何对Windows Server 2008上的ARP缓存进行管理.在微软最新发布的服务器操作系统中,ARP缓存被改称为邻机缓存;尽管它相比以前的服务器版本,实际操作方式 ...

  6. 在vb中使用Iphlpapi.dll获取网络信息(下)

    (转上版)http://miaozk2006.blog.163.com/blog/static/382470582011111391326440/ 5.运行时截图: 第十四节 返回本机网络接口数量 1 ...

  7. 图解ARP协议(三)ARP防御篇-如何揪出“内鬼”并“优雅的还手”?

    一.ARP防御概述 通过之前的文章,我们已经了解了ARP攻击的危害,黑客采用ARP软件进行扫描并发送欺骗应答,同处一个局域网的普通用户就可能遭受断网攻击.流量被限.账号被窃的危险.由于攻击门槛非常低, ...

  8. 计算机网络数据通信部分之网络层ARP报文分析

    ARP (地址解析协议) 即(Address Resolution Protocol),是根据IP地址获取物理地址的一个TCP/IP协议.主机发送信息时将包含目标IP地址的ARP请求广播到网络上的所有 ...

  9. cisco 交换机 获取 转发表_思科交换机端口号、终端IP地址和MAC地址的互查

    很多时候,在排查和定位网络故障或者梳理网络架构情况时,你可以直接获取的信息有限,比如你只知道用户的IP或MAC而不知道它连到了交换机哪个端口,或者你知道故障点在交换机某个端口上,但不知道这个端口连到了 ...

  10. 图解ARP协议(三)ARP防御篇-如何揪出“内鬼”并“优雅的还手”

    转自 https://blog.51cto.com/chenxinjie/1961255 一.ARP防御概述 通过之前的文章,我们已经了解了ARP攻击的危害,黑客采用ARP软件进行扫描并发送欺骗应答, ...

最新文章

  1. HSV的数据结构各分量H S V的直观理解其实就是对应图片位置的的像素一一对应的矩阵表示
  2. 给出一种符号表的组织方式和结构设计,要考虑数组类型和函数(不得与课件上的雷同)
  3. dji大疆机器人冬令营_2019高中生机器人夏令营开营 精英高中生汇聚
  4. JavaScript中this指针指向的彻底理解
  5. Oracle修改数据时提示“record is locked by another user”的解决办法
  6. 理解 Nginx HTTP 代理, 负载均衡, Buffering, Caching
  7. mysql的复制详解
  8. 转载:互联网盈利模式
  9. 用友 U8 word模板修改
  10. SQL数据分析常用案例总结
  11. 基于MODBUS总线的变频调速系统设计与实现
  12. 电子设计(4)高电平、低电平复位电路
  13. 设定窗体显示状态(ShowWindow)
  14. codeforces 417D Cunning Gena
  15. VisionPro相机操作类
  16. LeetCode 810 Chalkboard XOR Game【思维】
  17. 打印绕圈矩阵(C语言风格的代码)
  18. windows下使用VS2010编译jpeglib
  19. 2、controller介绍
  20. base64编码类源代码(C#)

热门文章

  1. AAC 音频数据结构实例分析:
  2. java轿煤悝炾厍桴,最让人放心的汉字笔画序库.doc
  3. 该填志愿了,国内大学计算机专业哪家强?
  4. 解决SSLHandshakeException :sun.security.validator.ValidatorException: PKIX path building failed:
  5. 【渝粤教育】广东开放大学 领导学基础 形成性考核 (38)
  6. mysql jion on 三表_MySQL 三表连接(join)
  7. bzoj 1467 exBSGS
  8. Flask基础--思维导图
  9. 新一轮支付革命,利楚扫呗的数据库优化之路
  10. java--------------