获得代理IP或客户端Ip

时间:2021-07-06 16:13:57

public static string GetIP()
        {
            // 优先取得代理IP
            string userHostAddress = HttpContext.Current.Request.ServerVariables     

        ["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(userHostAddress))
            {
                //没有代理IP则直接取客户端IP
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if ((userHostAddress != null) && !(userHostAddress == string.Empty))
            {
                return userHostAddress;
            }
            return "0.0.0.0";
        }