How to get a user's client IP address in ASP.NET?

前端 未结 19 2604
时光取名叫无心
时光取名叫无心 2020-11-22 00:26

We have Request.UserHostAddress to get the IP address in ASP.NET, but this is usually the user\'s ISP\'s IP address, not exactly the user\'s machine IP address

19条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:02

    public static class Utility
    {
        public static string GetClientIP(this System.Web.UI.Page page)
        {
            string _ipList = page.Request.Headers["CF-CONNECTING-IP"].ToString();
            if (!string.IsNullOrWhiteSpace(_ipList))
            {
                return _ipList.Split(',')[0].Trim();
            }
            else
            {
                _ipList = page.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"];
                if (!string.IsNullOrWhiteSpace(_ipList))
                {
                    return _ipList.Split(',')[0].Trim();
                }
                else
                {
                    _ipList = page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (!string.IsNullOrWhiteSpace(_ipList))
                    {
                        return _ipList.Split(',')[0].Trim();
                    }
                    else
                    {
                        return page.Request.ServerVariables["REMOTE_ADDR"].ToString().Trim();
                    }
                }
            }
        }
    }
    

    Use;

    string _ip = this.GetClientIP();
    

提交回复
热议问题