[Asp.Net]獲取客戶端ip和mac地址


摘要

有時候,我們需要獲取客戶端的一些信息,以便進行統計。比如:客戶端的唯一標識,ip等信息

IP

通過獲取HTTP_X_FORWARDED_FOR,或者REMOTE_ADDR可以獲取客戶端的ip。

        private string GetClientIP()
        {

            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }

測試

MAC

MAC(Medium/Media Access Control)地址,用來表示互聯網上每一個站點的標識符,采用十六進制數表示,共六個字節(48位)。其中,前三個字節是由IEEE的注冊管理機構RA負責給不同廠家分配的代碼(高位24位),也稱為“編制上唯一的標識符”(Organizationally Unique Identifier),后三個字節(低位24位)由各廠家自行指派給生產的適配器接口,稱為擴展標識符(唯一性)。

        [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);

        private string GetClientMAC()
        {
            string mac_dest = string.Empty;
            // 在此處放置用戶代碼以初始化頁面
            try
            {
                string userip = Request.UserHostAddress;
                string strClientIP = Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP); //目的地的ip 
                Int32 lhost = inet_addr("");   //本地服務器的ip 
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                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));
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return mac_dest;
        }

測試發現輸出的mac地址和通過命令config/all查到的mac地址相同。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM