How do I get the correct IP from HTTP_X_FORWARDED_FOR if it contains multiple IP Addresses?

前端 未结 4 2000
北海茫月
北海茫月 2020-11-29 03:29

If Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"] returns multiple ip\'s, which one do I take and how would I do it in c#? It is my understanding that if it is blank or

4条回答
  •  悲&欢浪女
    2020-11-29 03:54

    The actual client IP should be the left-most IP address in the header value. You can extract it into an environment variable using a regex:

    SetEnvIf X-Forwarded-For "^(\d{1,3}+\.\d{1,3}+\.\d{1,3}+\.\d{1,3}+).*" XFFCLIENTIP=$1
    

    Note the use of $1 to set the XFFCLIENTIP environment variable to hold the contents of the first group in the regex (in the parentheses).

    As an example of using this, you can define a log format that uses the variable: this example is one we use internally at nearmap.com, so it logs extra information, but the bit you want is the %{XFFCLIENTIP}e at the beginning. Note the env=XFFCLIENTIP at the end of the line, which means this format is only used if the environment variable is set.

    CustomLog /var/log/apache2/access.log "%{XFFCLIENTIP}e \"%{session}C\" \"%{nearmapuid}C\" %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" env=XFFCLIENTIP
    

提交回复
热议问题