获取用户的IP地址

时间:2010-04-12 09:22:15

标签: asp.net ip-address

如何获取当前访问者的IP地址?

5 个答案:

答案 0 :(得分:25)

编辑:还发现了一个与IP相关的http标头here的有趣问题。

Edit2:正如我在上面提供的评论和链接中所提到的,HTTP_X_FORWARDED_FOR标头可能包含多个以逗号分隔的IP地址。我没有遇到这种情况,但想要对我的答案进行一些修正。

我使用此代码获取IP地址(如果因某种原因失败,则会返回IPAddress.None值):

    /// <summary>
    /// Gets the IP address of the request.
    /// <remarks>
    /// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
    /// <summary>
    /// Gets the IP address of the request.
    /// <remarks>
    /// This method is more useful than built in because in some cases it may show real user IP address even under proxy.
    /// The <see cref="System.Net.IPAddress.None" /> value will be returned if getting is failed.
    /// </remarks>
    /// </summary>
    /// <param name="request">The HTTP request object.</param>
    /// <returns></returns>
    public static IPAddress GetIp(this HttpRequest request)
    {
        string ipString;
        if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
        {
            ipString = request.ServerVariables["REMOTE_ADDR"];
        }
        else
        {
            ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                .FirstOrDefault();
        }

        IPAddress result;
        if (!IPAddress.TryParse(ipString, out result))
        {
            result = IPAddress.None;
        }

        return result;
    }

答案 1 :(得分:20)

HttpContext.Current.Request.UserHostAddress;

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

答案 2 :(得分:2)

Request.UserHostAddress

答案 3 :(得分:1)

public String GetIP()
{
    string ipString;
    if (string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
    {
        ipString = Request.ServerVariables["REMOTE_ADDR"];
    }
    else
    {
        ipString = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
    }
    return ipString;
}

首先尝试查找代理IP,如果它为null,我们可以获得该系统IP

答案 4 :(得分:0)

尝试使用此方法获取用户的外部IP地址..

public static string getExternalIp()
    {
        try
        {

            string externalIP;
            externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
            externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                         .Matches(externalIP)[0].ToString();
            return externalIP;
        }
        catch { return null; }
    }