Demo-C/Tech/ArpUtil.cs

129 lines
4.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace PlumByteUI_Learn
{
public class ArpUtil
{
/// <summary>
/// 引入windowsAPI
/// </summary>
//用于转换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 = inet_addr(ip); //将IP地址从 点数格式转换成无符号长整型
long macinfo = new long();
int len = 6;
//SendARP函数发送一个地址解析协议(ARP)请求获得指定的目的地IPv4地址相对应的物理地址
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 -n 192.168.0.105")
{
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 oArp
where !string.IsNullOrEmpty(piece)
select piece).ToArray();
if (pieces.Length == 3)
{
//pieces[1]Mac
//pieces[0]IP
list.Add(new string[2] { pieces[1], pieces[0] });
}
}
}
return list;
}
catch (Exception ex)
{
throw new Exception("IPInfo: Error Parsing 'arp -a' results", ex);
}
}
}
}