• 获取IP地址方法


    //方法一
    HttpContext.Current.Request.UserHostAddress; 
    
    //方法二
    HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    
    //方法三
    string strHostName = System.Net.Dns.GetHostName();
    string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
    

      

      但如果客户端是使用代理服务器来访问,那取到的就是代理服务器的IP地址,而不是真正的客户端IP地址。

      要想透过代理服务器取得客户端的真实IP地址,就要使用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 来读取。

      不过要注意的事,并不是每个代理服务器都能用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 来读取客户端的真实 IP,有些用此方法读取到的仍然是代理服务器的IP。

      还有一点需要注意的是:如果客户端没有通过代理服务器来访问,那么用 Request.ServerVariables ("HTTP_X_FORWARDED_FOR") 取到的值将是空的。因此,如果要在程序中使用此方法,可以这样处理:

    if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // 服务器, using proxy 
      { 
      得到真实的客户端地址 
      ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP. 
      } 
      else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP 
      { 
      得到服务端的地址 
      ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP. 
      }

    有些客户端会因为“header_access deny”的安全设置而不发给我们Ip

  • 相关阅读:
    表达式for loop
    用户输入
    字符编码
    变量字符编码
    Python安装
    Python 2 or 3?
    Python解释器
    2017中国大学生程序设计竞赛
    Educational Round 27
    Round #429 (Div.2)
  • 原文地址:https://www.cnblogs.com/blosaa/p/2957248.html
Copyright © 2020-2023  润新知