Back

获取客户端的真实ip代码改进

现在系统中常用的获取客户端真实ip的代码如下:

// 获取IP地址
protected string GetIPAddress()
{
    string result = "";
    try
    {
        //透过代理取客户端ip
        result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? "";
        if (result == "")
        {
            //连接主机ip
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] ?? "";
        }
        if (result == "")
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
    }
    catch (Exception ex)
    {
    }
    return result;
}

这段代码有两个问题: 1、根据这篇文章说明,当请求经常多个代理时,HTTP_X_FORWARDED_FOR可能会附加上多个服务器ip,格式如下:

X-Forwarded-For: client1, proxy1, proxy2, …

正确的客户端ip应该只是第一个ip地址

2、当用户手机是用CMWAP访问网站时,上面代码返回的是10.xxx的私有网络ip,而真实的服务器ip是在REMOTE_ADDR中,如下图所示: 所以对于获取来的ip,需要做是否私有网络ip的判断。所有私有网络的ip段如下:

private static readonly long[,] privateIpRange = {    //私有网络ip段,长整形表示
    {0,50331647},                   //{"0.0.0.0","2.255.255.255"},
    {167772160,184549375},          //{"10.0.0.0","10.255.255.255"},
    {2130706432,2147483647},        //{"127.0.0.0","127.255.255.255"},
    {2851995648,2852061183},        //{"169.254.0.0","169.254.255.255"},
    {2886729728,2887778303},        //{"172.16.0.0","172.31.255.255"},
    {3221225984,3221226239},        //{"192.0.2.0","192.0.2.255"},
    {3232235520,3232301055},        //{"192.168.0.0","192.168.255.255"},
    {4294967040,4294967295}};       //{"255.255.255.0","255.255.255.255"}