C#获取客户端IP地址

using System.Text.RegularExpressions;
using System.Web;

namespace UtilityFactory
{
    public class IPUtility
    {

        /// <summary>
        /// 获取客户端IP地址(无视代理)
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress()
        {
            string userHostAddress = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            
            if (!string.IsNullOrEmpty(userHostAddress) && Regex.IsMatch(userHostAddress, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"))
            {
                return userHostAddress;
            }
            return string.Empty;
        }

    }
}
发布了60 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_24432127/article/details/90266710