C # Get real IP Address implementation method

Source: Internet
Author: User
Tags servervariables

In general, the usual way to get a user's IP address is:

1 stringIpAddress ="";2 if((httpcontext.current.request.servervariables["http_x_forwarded_for"]!=NULL 3&& httpcontext.current.request.servervariables["http_x_forwarded_for"] !=String.Empty))4 {5ipaddress=httpcontext.current.request.servervariables["http_x_forwarded_for"] ;6 }7 Else8 { 9httpcontext.current.request.servervariables["REMOTE_ADDR"]; Ten}
View Code

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.

How to get the real IP of the user:

1 usingSystem;2 usingSystem.Data;3 usingSystem.Configuration;4 usingsystem.web;5 usingSystem.Web.Security;6 usingSystem.Web.UI;7 usingSystem.Web.UI.WebControls;8 usingSystem.Web.UI.WebControls.WebParts;9 usingSystem.Web.UI.HtmlControls;Ten usingSystem.Text.RegularExpressions; One namespaceCommon A { -     /// <summary> -     ///Summary description of IPAddress the     /// </summary> -  Public classIPAddress:System.Web.UI.Page - { -      Public StaticInt64 Todenaryip (stringIP) +     { -Int64 _int64 =0; +         string_IP =IP; A         if(_ip. LastIndexOf (".") >-1 ) at         { -             string[] _iparray = _ip. Split ('.' ); -_int64 = Int64.parse (_iparray. GetValue (0). ToString ()) * the* the* the+ Int64.parse (_iparray. GetValue (1). ToString ()) * the* the+ Int64.parse (_iparray. GetValue (2). ToString ()) * the+ Int64.parse (_iparray. GetValue (3). ToString ())-1; -         } -         return_int64; -     } in     /// <summary> -     //// IP Decimal to     /// </summary> +      Public StaticInt64 Denaryip -     { the         Get { *Int64 _int64 =0; $             string_IP =IP;Panax Notoginseng             if(_ip. LastIndexOf (".") >-1 ) -             { the                 string[] _iparray= _ip. Split ('.' ); +_int64 = Int64.parse (_iparray. GetValue (0). ToString ()) * the* the* the+ Int64.parse (_iparray. GetValue (1). ToString ()) * the* the+ Int64.parse (_iparray. GetValue (2). ToString ()) * the+ Int64.parse (_iparray. GetValue (3). ToString ())-1; A             } the             return_int64; +         } -     } $      Public Static stringIP $     { -         Get -         { the             stringresult =String.Empty; -result = httpcontext.current.request.servervariables["http_x_forwarded_for"];Wuyi             if(Result! =NULL&& Result! =String.Empty) the             { -                //may have an agent Wu                 if(result.) IndexOf (".") == -1)//no "." Must be a non-IPv4 format -result =NULL; About                 Else $                 { -                     if(result.) IndexOf (",") != -1 ) -                     { -                          //there are ",", estimated multiple agents. Take the first IP that is not an intranet.  Aresult = result. Replace (" ",""). Replace ("","" ); +                         string[] Temparyip = result. Split (",;". ToCharArray ()); the                          for(inti =0; I < Temparyip. Length; i++ ) -                         { $                             if(Isipaddress (temparyip[i]) the&& Temparyip[i]. Substring (0,3) !="." the&& Temparyip[i]. Substring (0,7) !="192.168" the&& Temparyip[i]. Substring (0,7) !="172.16." ) the                             { -                                 returnTemparyip[i];//find an address that is not an intranet in                             } the                         } the                     } About                     Else if(isipaddress (Result))//Proxy is the IP format the                         returnresult; the                     Else theresult =NULL;//content in Agent non-IP, take IP +                 } -             } 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"];Bayi             the             if(NULL= = Result | | result = =String.Empty) theresult = httpcontext.current.request.servervariables["REMOTE_ADDR"]; -             if(Result = =NULL|| result = =String.Empty) -result =HttpContext.Current.Request.UserHostAddress; the             returnresult; the         } the     } the      //whether the IP format -      Public Static BOOLIsipaddress (stringstr1) the     { the         if(str1 = =NULL|| STR1 = =string. Empty | | Str1. Length <7|| Str1. Length > the)return false; the         stringRegformat =@"^\\d{1,3}[\\.] \\d{1,3}[\\.] \\d{1,3}[\\.] \\d{1,3}$";94Regex regex =NewRegex (Regformat, regexoptions.ignorecase); the         returnregex. IsMatch (STR1); the     } the }98}
View Code

C # Get real IP Address implementation method

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.