首页 > 代码库 > 获取用户的IP地址和本机IP4地址

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

/// <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;
}