C#WindowsAPI库 > Iphlpapi


Iphlpapi.dll中的一些方法


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace WindowsAPI
{
    /// <summary>
    /// Iphlpapi.dll中的一些方法
    /// </summary>
    public class Iphlpapi
    {
        /// <summary>
        /// 获取一个ip对应的mac地址
        /// </summary>
        /// <param name="ipstr">任意ip</param>
        /// <returns>mac地址字符串,不带-</returns>
        public static string GetMacAddrFrom(string ipstr)
        {
            Int32 remote = Ws2_32.inet_addr(ipstr);
            Int64 macInfo = new Int64();
            Int32 length = 6;
            _ = SendARP(remote, 0, out macInfo, out length);
            string mac = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
            char[] cs = new char[12];
            cs[0] = mac[10];
            cs[1] = mac[11];
            cs[2] = mac[8];
            cs[3] = mac[9];
            cs[4] = mac[6];
            cs[5] = mac[7];
            cs[6] = mac[4];
            cs[7] = mac[5];
            cs[8] = mac[2];
            cs[9] = mac[3];
            cs[10] = mac[0];
            cs[11] = mac[1];
            return new string(cs);
        }
        /// <summary>
        /// 获取远程终端的mac地址
        /// </summary>
        /// <param name="DestIP"></param>
        /// <param name="SrcIP"></param>
        /// <param name="MacAddr"></param>
        /// <param name="PhyAddrLen"></param>
        /// <returns></returns>
        [DllImport("Iphlpapi.dll")]
        public static extern int SendARP(Int32 DestIP, Int32 SrcIP, out Int64 MacAddr, out Int32 PhyAddrLen);
    }
}