UserHostAddress gives wrong IPs

后端 未结 7 1580
[愿得一人]
[愿得一人] 2021-01-02 03:26

I collect statistics on IP addresses from where users visit my site and I have noticed what there are only two IP addresses presented, 172.16.16.1 and 172.16.16.248. The pro

相关标签:
7条回答
  • 2021-01-02 04:05

    Building on tomfannings answer...

     public static string ClientIp(this HttpRequestBase @this) {
      var clientIp = string.Empty;
      string forwardedFor = @this.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
      if (string.IsNullOrWhiteSpace(forwardedFor)) {
        clientIp = @this.ServerVariables["REMOTE_ADDR"];
      } else {
    
        var array = forwardedFor
          .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
          .Select(s => s.Trim());
    
        foreach (var element in array) {
          if (element.IsValidIp4() || element.IsValidIp6()) {
            clientIp = element;
            break;
          }
        }
      }
      return clientIp;
    }
    
    public static bool IsValidIp4(this string @this) {
      var pattern = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$");
      return pattern.IsMatch(@this);
    }
    
    public static bool IsValidIp6(this string @this) {
      var pattern = new Regex(@"^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/(d|dd|1[0-1]d|12[0-8]))$");
      return pattern.IsMatch(@this);
    }
    
    0 讨论(0)
提交回复
热议问题