Example:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Text. RegularExpressions;
Namespace DiLian
{
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
Label5.Text = GetIP ();
}
# Region bool IsIPAddress (str1) judge whether it is an IP format
/**/
/// <Summary>
/// Determine whether the IP address format is 0.0.0.0
/// </Summary>
/// <Param name = "str1"> IP address to be determined </param>
/// <Returns> true or false </returns>
Private bool IsIPAddress (string str1)
{
If (str1 = null | str1 = string. Empty | str1.Length <7 | str1.Length> 15) return false;
String regformat = @ "^ \ d {1, 3} [\.] \ d {1, 3} [\.] \ d {1, 3} [\.] \ d {1, 3} $ ";
Regex regex = new Regex (regformat, RegexOptions. IgnoreCase );
Return regex. IsMatch (str1 );
}
# Endregion
Private string GetIP ()
{
String result = String. Empty;
Result = HttpContext. Current. Request. ServerVariables ["HTTP_X_FORWARDED_FOR"];
If (result! = Null & result! = String. Empty)
{
// A proxy may exist.
If (result. IndexOf (".") =-1) // No "." is definitely not in IPv4 format.
Result = null;
Else
{
If (result. IndexOf (",")! =-1)
{
// There are ",", and multiple proxies are estimated. Obtain the first IP address that is not an intranet IP address.
Result = result. Replace ("", ""). Replace ("'","");
String [] temparyip = result. Split (",;". ToCharArray ());
For (int I = 0; I <temparyip. Length; I ++)
{
If (IsIPAddress (temparyip [I])
& Temparyip [I]. Substring (0, 3 )! = "10 ."
& Temparyip [I]. Substring (0, 7 )! = "192.168"
& Temparyip [I]. Substring (0, 7 )! = "172.16 .")
{
Return temparyip [I]; // locate an address that is not an intranet address
}
}
}
Else if (IsIPAddress (result) // The proxy is in the IP format
Return result;
Else
Result = null; // The content in the proxy is not an IP address and the IP address is used.
}
}
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"];
If (null = result | result = String. Empty)
Result = HttpContext. Current. Request. ServerVariables ["REMOTE_ADDR"];
If (result = null | result = String. Empty)
Result = HttpContext. Current. Request. UserHostAddress;
Return result;
}
}
}
Copy and save it. You can try it very well. The small Editor tests the ChinaNetCenter cdn acceleration.