获取用户的IP地址和本机IP4地址

时间:2014-04-29 10:16:45   收藏:0   阅读:397

/// <summary>
/// 获取用户的IP地址
/// </summary>
/// <returns></returns>
public static string GetIPAddress()
{
string user_IP = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
}
}
else
{
//IP地址
//本机地址信息
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(Dns.GetHostName());

//循环判断获取IP4地址
for (int icount = 0; icount < ipEntry.AddressList.Length; icount++)
{
if (ipEntry.AddressList[icount].AddressFamily == AddressFamily.InterNetwork)
{
user_IP = ipEntry.AddressList[icount].ToString();
break;
}
}
}
return user_IP;
}

获取用户的IP地址和本机IP4地址,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!