C # Get User IP address (reprint)

Source: Internet
Author: User
Tags servervariables

"ASP. NET development "Get client IP address via C #

Description: The content of this article is my blog in the park and the MSDN discussion area of the material, and then through their own actual testing, the original content of their own to tell the truth is very few , write this is to record their work in the project, but also want to initiate. The referenced blog post and its author are mentioned below. until after their own HTTP, TCP/IP and other knowledge in-depth, we must come here to discuss this content in depth.

First, the noun

First, let's talk about some of the following nouns.

In web development, most of us are accustomed to using some of the properties in the HTTP request header to get the IP address of the client, the common attributes are remote_addr,Http_via , and http_x_forwarded_ For.

The meaning of These three attributes is probably the same: (Excerpt from the Internet, please correct me)

REMOTE_ADDR: The value of this property is the IP of the client and the server "handshake". If you use anonymous proxy, REMOTE_ADDR displays the IP of the proxy server.

X-forwarded-for: is the HTTP request header field that is used to identify the most original IP address of the client that is connected to the Web server through an HTTP proxy or load balancer.

The validity of the xff depends on the authenticity of the connection original IP address provided by the proxy server, so the effective use of XFF should ensure that the proxy server is trustworthy, such as by establishing a trusted server whitelist.

The general format of this HTTP header is as follows:

  X-forwarded-for:client1, Proxy1, Proxy2

The value of which is separated by commas + spaces, the leftmost (CLIENT1) is the IP address of the most original client, and the proxy server adds the requested source IP address to the right when each request is received successfully. In the above example, this request successfully passed through three proxy servers: Proxy1, Proxy2 and Proxy3. The request was issued by CLIENT1 and reached Proxy3 (Proxy3 could be the end of the request). When the request has just been issued from CLIENT1, the Xff is empty, the request is sent to Proxy1, Client1 is added to the Xff by Proxy1, and then the request is sent to Proxy2; Proxy2 is added to Proxy1 when Xff is passed. The request is then sent to Proxy3, Proxy3, Proxy2 is added to the XFF, then the requested whereabouts are unknown, if the proxy3 is not the request endpoint, the request will continue to be forwarded.

Since it is easy to forge this field, you should use the X-forwarded-for field with caution. Normally the last IP address in xff is the IP address of the last proxy server, which is usually a reliable source of information.

(A complete introduction to X-forwarded-for in the wiki: http://zh.wikipedia.org/wiki/X-Forwarded-For)

As for what the value of the attribute is when using these attributes, a blog post is found on the Web: the difference between the three attributes of the user's IP address (unknown to the original author).

  

In ASP. NET, another way to get the IP address of the client is through the UserHostAddress property in the Request object . In the MSDN Library, this attribute is interpreted as: the property value is the IP address of the remote client.

If the client uses a proxy server, the Request.userhostaddress property obtains the IP address of the proxy server.

Second, the method

Okay, so much of the conceptual stuff, let's talk about the way it's implemented.

The idea of most methods on the net is: If there is proxy IP, get the proxy IP first, otherwise get the IP of the connecting client, or turn over, get the IP of the connecting client first, if get failed, get proxy IP.

The following methods refer to the Post ASP. NET Get client IP (author Comeonfyz)

-----------------------------------------------------------------------------------------------------------

<summary>///Get client IP address///</summary>///<returns> return loopback address </returns>public static if failed String GetIP () {///If the client is using a proxy server, use Http_x_forwarded_for to locate the client IP address string userhostaddress = HttpContext.Current.Reques t.servervariables["Http_x_forwarded_for"]. ToString (). Split (', ') [0].    Trim (); Otherwise directly read REMOTE_ADDR Gets the client IP address if (string.    IsNullOrEmpty (userhostaddress)) {userhostaddress = httpcontext.current.request.servervariables["REMOTE_ADDR"]; }//Before both fail, the IP address is obtained using the Request.userhostaddress property, but at this point it is not possible to determine whether the IP is a client IP or proxy IP if (string.    IsNullOrEmpty (userhostaddress)) {userhostaddress = HttpContext.Current.Request.UserHostAddress; }//finally determine if the acquisition was successful and check the format of the IP address (it is important to check its format) if (!string.    IsNullOrEmpty (userhostaddress) && IsIP (userhostaddress)) {return userhostaddress; } return "127.0.0.1";} <summary>///Check IP address format///</summary>///<param name= "IP" ></param>///<returns></ Returns>public StaticBOOL IsIP (string IP) {return System.Text.RegularExpressions.Regex.IsMatch (IP, @ "^ (2[0-4]\d|25[0-5]|[ 01]?\d\d?) \.) {3} (2[0-4]\d|25[0-5]| [01]?\d\d?] $");}

-----------------------------------------------------------------------------------------------------------

However, there is a serious flaw in this, that is, as Daniel Kingthy in his blog using Http_x_forwarded_for to obtain the client IP of the serious consequences, said, "Http_x_forwarded_for" This value is obtained by the HTTP header "X_ Forwarded_for "property, malicious attackers can easily forge IP addresses, and as mentioned above, the effectiveness of XFF depends on the authenticity of the connection original IP address provided by the proxy server, so the effective use of XFF should ensure that the proxy server is trustworthy. However, as a developer, we do not know the authenticity of the user's IP address, it is difficult to distinguish the credibility of the proxy server.

Therefore, the synthesis of all aspects of the information, my personal thoughts and Daniel Kingthy the same: ignoring the agent .

-----------------------------------------------------------------------------------------------------------

 1//<summary> 2///Get Client IP address (ignore proxy) 3//</summary> 4//<returns> return address if failed </re Turns> 5 public static string Gethostaddress () 6 {7 String userhostaddress = HttpContext.Current.Reque St. userhostaddress; 8 9 if (string. IsNullOrEmpty (userhostaddress)) {userhostaddress = httpcontext.current.request.servervariables["R Emote_addr "];12}13 14//Last to determine whether the acquisition was successful and to check the format of the IP address (it is important to check its format) if (!string.         IsNullOrEmpty (userhostaddress) && IsIP (userhostaddress)) (userhostaddress;18)     }19 return "127.0.0.1",}21//<summary>23//Check IP address format///&LT;/SUMMARY&GT;25  <param name= "IP" ></param>26//<returns></returns>27 public static bool IsIP (string IP) {System.Text.RegularExpressions.Regex.IsMatch return (IP, @ "^ (2[0-4]\d|25[0-5]|[ 01]?\d\d?) \.) {3} (2[0-4]\d|25[0-5]| [01]?\d\d?] $ "); 30}

-----------------------------------------------------------------------------------------------------------

Iii. Summary

Ignoring the proxy server is certainly not the best solution, and if the project needs to be clear about the client's real address, it must not ignore the proxy server.

In addition, I also asked Artech Daniel to ask this question, although he did not have a thorough study of these, but he also believes that no IP access is completely trustworthy, because this is the TCP/IP protocol itself.

Attach Artech Daniel to me a copy of the information, share sharing. Http://www.symantec.com/connect/articles/ip-spoofing-introduction

 

Reprint Source: https://www.cnblogs.com/stay-foolish/archive/2012/05/01/2475071.html

C # Get User IP address (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.