Asp.net obtains the Client IP Address

Source: Internet
Author: User

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.

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.