C#获取客户端Ip和MAC地址

 

获取客户端IP

public static string GetClientIp()
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//是否有代理服务器
                return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            else
                return System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }

获取客户端MAC

[DllImport("Iphlpapi.dll")]
        static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
        [DllImport("Ws2_32.dll")]
        static extern Int32 inet_addr(string ipaddr);
        public static string getMacAddr_Remote(string RemoteIP)
        {
            StringBuilder macAddress = new StringBuilder();
            try
            {
                Int32 remote = inet_addr(RemoteIP);
                Int64 macInfo = new Int64();
                Int32 length = 6;
                SendARP(remote, 0, ref macInfo, ref length);
                string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                    {
                        macAddress.Append(temp.Substring(x - 2, 2));
                    }
                    else
                    {
                        macAddress.Append(temp.Substring(x - 2, 2) + "-");
                    }
                    x -= 2;
                }
                return macAddress.ToString();
            }
            catch
            {
                return macAddress.ToString();
            }
        }

 获取服务器MAC地址 

 public string GetMacAddress()
        {
            try
            {
                string mac = "";
                ManagementObjectSearcher nisc = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration");
                foreach (ManagementObject nic in nisc.Get())
                {
                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                    {
                        mac = nic["MACAddress"].ToString().Replace(':', '-');
                        break;
                    }
                }
                return mac;
            }
            catch
            {
                return "unknow";
            }
        }

 

你可能感兴趣的:(C#)