随着网络的广泛发展,有时候到处要用到获取Ip的方法,下面是一个比较好的获取客户端Ip的方法,希望对您有用。
public static string GetIP()
{//如果客户端使用了代理服务器,则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? "";
if (!string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = userHostAddress.Split(',')[0].Trim();
}
//否则直接读取REMOTE_ADDR获取客户端IP地址
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
//前两者均失败,则利用Request.UserHostAddress属性获取IP地址,但此时无法确定该IP是客户端IP还是代理IP
if (string.IsNullOrEmpty(userHostAddress))