C # take real IP address and analysis

Source: Internet
Author: User
Tags servervariables

I found from the csdn, feeling very useful, I picked up **************

At present, the so-called "take Real IP Address" method, there are bugs, do not take into account the situation of multi-layer transparent agent.
Most of the code is similar:

String IpAddress = (httpcontext.current.request.servervariables["Http_x_forwarded_for"]!=null
&& httpcontext.current.request.servervariables["Http_x_forwarded_for"]!=string.empty)
? httpcontext.current.request.servervariables["Http_x_forwarded_for"]
: httpcontext.current.request.servervariables["REMOTE_ADDR"];


In fact, the above code only trial with the user only use 1 layer agent, if the user has 2 layers, 3 layer http_x_forwarded_for value is: "Native real ip,1 layer proxy ip,2 layer proxy IP,.....", If the length of the IP field in your data is very small (15 bytes), the database will get an error.

In practical applications, there are few such users because of the relatively small number of transparent proxies used.

Other applications, now more and more sites using agent acceleration, such as Sina, Sohu News are using squid as an agent, using more than one server shunt. Squid itself is similar to transparent proxy, will send "Http_x_forwarded_for", Http_x_forwarded_for includes the customer's IP address, if the customer has used a transparent proxy, then the program "Http_x_ Forwarded_for "is comprised of two IP addresses. (I have encountered 3 IP addresses, 4 have not encountered)

So the "real" IP address should also be judged "http_x_forwarded_for" whether there is "," comma, or whether the length is very long (more than 15 bytes xxx.xxx.xxx.xxx).

So the code should look like this:

1 /**//// <summary> 2 ///get the client real IP. If you have an agent, take the first non-intranet address3 /// </summary> 4  Public Static stringIPAddress5 { 6     Get 7     { 8         stringresult =String.Empty;9result = httpcontext.current.request.servervariables["http_x_forwarded_for"]; Ten         if(result!=NULL&&result!=String.Empty) One         {  A             //may have an agent -             if(result.) IndexOf (".")==-1)//no "." Must be a non-IPv4 format -result =NULL;  the             Else  -             {  -                 if(result.) IndexOf (",")!=-1)  -                 {  +                     //there are ",", estimated multiple agents. Take the first IP that is not an intranet.  -result = result. Replace (" ",""). Replace (""","");  +                     string[] Temparyip = result. Split (",;". ToCharArray ());  A                      for(intI=0; I<temparyip. length;i++)  at                     {  -                         if(Text.isipaddress (temparyip[i]) -&& Temparyip[i]. Substring (0,3)!="."  -&& Temparyip[i]. Substring (0,7)!="192.168"  -&& Temparyip[i]. Substring (0,7)!="172.16.")  -                         {  in                             returnTemparyip[i];//find an address that is not an intranet -                         }  to                     }  +                 }  -                 Else if(text.isipaddress (Result))//Proxy is the IP format the                     returnresult; *                 Else  $result =NULL;//content in Agent non-IP, take IPPanax Notoginseng             }  -         }  the         stringIpAddress = (httpcontext.current.request.servervariables["http_x_forwarded_for"]!=NULL&& httpcontext.current.request.servervariables["http_x_forwarded_for"]!=string.empty)? httpcontext.current.request.servervariables["http_x_forwarded_for"]:httpcontext.current.request.servervariables["REMOTE_ADDR"];  +          if(NULL= = Result | | result = =String.Empty) Aresult = httpcontext.current.request.servervariables["REMOTE_ADDR"];  the         if(Result = =NULL|| result = =String.Empty) +result =HttpContext.Current.Request.UserHostAddress; -         returnresult; $     }  $}

Take the disadvantage of "http_x_forwarded_for".

Http_x_forwarded_for is part of the header in the HTTP protocol and does not affect TCP traffic. In other words, the client can send http_x_forwarded_for of arbitrary content, which is the fake IP. The simplest is the IP record of the Web program, originally to record the real IP, but by "hackers" deception. When your application logs the client's access IP, denies or allows access to some of the IP, the error log will be faulted or even manslaughter.

Therefore, the necessary security log should record the full "http_x_forwarded_for" (at least assign 3*15+2 bytes to the fields in the database to record at least 3 IPs) and "REMOTE_ADDR". It is also essential to check the IP format of the http_x_forwarded_for.

Attached: (text is a class I have customized, isipaddress is one of the methods to determine whether the IP address format)

1 #regionBOOL Isipaddress (STR1) determines whether it is an IP format2 /**//// <summary>3 ///determine if the IP address format is 0.0.0.04 /// </summary>5 /// <param name= "str1" >IP address to be judged</param>6 /// <returns>true or False</returns>7  Public Static BOOLIsipaddress (stringstr1)8 {9     if(str1==NULL|| str1==string. empty| | Str1. length<7|| Str1. Length> the)return false; Ten     stringRegformat =@"^\d{1,3}[\.] \d{1,3}[\.] \d{1,3}[\.] \d{1,3}$"; OneRegex regex =NewRegex (regformat,regexoptions.ignorecase); A     returnregex. IsMatch (STR1); - } - #endregion

C # take real IP address and analysis

Related Article

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.