获取客户机MAC地址 根据IP地址 获取机器的MAC地址 / 获取真实Ip地址

        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
        /// <summary>
        /// 获取客户机MAC地址  根据IP地址 获取机器的MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetBarMACIP(string strIP)
        {
            //MAC信息
            string mac_dest = "";
            try
            {
                int ldest = inet_addr(strIP); //目的地的ip 
                int lhost = inet_addr("");   //本地服务器的ip 
                Int64 macinfo = new Int64();
                int len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                if (mac_src == "0")
                {
                    return "1";
                }
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }

                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
                return mac_dest;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 取得IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIp()
        {
            string str = "";
            //穿过代理服务器取远程用户真实IP地址:
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                str = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            else
                str = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            return str;
        }
原文地址:https://www.cnblogs.com/LJP-JumpAndFly/p/12009562.html