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

前端 未结 19 2556
时光取名叫无心
时光取名叫无心 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条回答
  •  无人共我
    2020-11-22 00:52

    UPDATE: Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:

        private string GetUserIP()
        {
            string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
            if (!string.IsNullOrEmpty(ipList))
            {
                return ipList.Split(',')[0];
            }
    
            return Request.ServerVariables["REMOTE_ADDR"];
        }
    

提交回复
热议问题