Serious consequences of using HTTP? X? Forwarded? For to get client IP


In web development, we may be accustomed to using the following code to obtain the IP address of the client:
C# code

Copy codeThe code is as follows:
//Priority to obtain proxy IP
string IP = Request.ServerVariables[“HTTP_X_FORWARDED_FOR“];
if (string.IsNullOrEmpty(IP)) {
//If there is no proxy IP, connect to the client IP directly
IP = Request.ServerVariables[“REMOTE_ADDR”];

The above code seems to be normal. Unfortunately, there is a hidden danger here!! because the value of “http ﹐ forward ﹐ for” is obtained by obtaining the “x ﹐ forward ﹐ for” attribute of HTTP header. So here is a method for malicious saboteurs: IP address can be forged!!
Here is the test code:

Copy codeThe code is as follows:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(“http://localhost/ip.aspx”);
request.Headers.Add(“X_FORWARDED_FOR”, “”);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string IP = stream.ReadToEnd();
request = null;

“IP. ASPX” file code:

Copy codeThe code is as follows:
//Priority to obtain proxy IP
string IP = Request.ServerVariables[“HTTP_X_FORWARDED_FOR”];
if (string.IsNullOrEmpty(IP))
//If there is no proxy IP, the client IP will be taken directly
IP = Request.ServerVariables[“REMOTE_ADDR”];

In this way, when accessing the ip.aspx file in the test code, “string IP = stream. Readtoend();” the IP data obtained by this code is “”!! (HA. In the real case, such IP address is certainly not the result we want. But in some voting systems, when an IP can only vote once, if we also use similar code to obtain the other IP and then judge. Ha ha. Restriction It’s invalid

Or if you use the above code to get the IP address and then don’t judge the data, you may be able to further destroy the data!!
For example, if you use the above code to obtain the IP address, you will have the following SQL statement:
string sql = “INSERT INTO (IP) VALUE (‘” + IP + “‘)”;
So maybe the destroyer can also inject SQL for data destruction!!

In this way, it seems that it is no longer advisable to use the attribute “http ﹣ x ﹣ forward ﹣ for” to obtain the client IP address. But if this method is not used, then those who actually use the proxy server can no longer obtain their real IP address (because some proxy servers will add the access user’s real IP address to the HTTP header “x ﹣ forward ﹣). Well, the reality is that In this way, something has gains and losses

Finally, my suggestion is not to use the above method to obtain the client IP. That is, do not pay attention to the agent situation. What is your suggestion???