Author: Jedi Wolf
Recently, 54 taoke netizens asked me how to obtain the Client IP address from asp.net, and how to determine whether asp.net is an IP address. Here I will share with you the frequently used methods for obtaining client IP addresses and checking whether they are IP addresses. I hope they will help you.
/// <Summary>
/// Obtain the IP address
/// </Summary>
/// <Returns> </returns>
Public static string GetIP ()
{
String userHostAddress = HttpContext. Current. Request. ServerVariables ["REMOTE_ADDR"];
If (string. IsNullOrEmpty (userHostAddress ))
{
UserHostAddress = HttpContext. Current. Request. ServerVariables ["HTTP_X_FORWARDED_FOR"];
}
If (string. IsNullOrEmpty (userHostAddress ))
{
UserHostAddress = HttpContext. Current. Request. UserHostAddress;
}
If (! String. IsNullOrEmpty (userHostAddress) & IsIP (userHostAddress ))
{
Return userHostAddress;
}
Return "127.0.0.1 ";
}
/// <Summary>
/// Check the IP address format
/// </Summary>
/// <Param name = "ip"> </param>
/// <Returns> </returns>
Public static bool IsIP (string ip)
{
Return System. Text. RegularExpressions. Regex. IsMatch (ip, @ "^ (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) \.) {3} (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) $ ");
}
The above code is used all the time in the project. You can feel free to use it. If there is any error, you can submit it in time for discussion and study. For more information, see www.54talk.cn.