获取IP

Method一.
private string GetClientIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}
/// <summary>
/// 获取本地Ip
/// </summary>
/// <returns></returns>
public string getLocalIP()
{
string strHostName = Dns.GetHostName(); //得到本机的主机名
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
string strAddr = ipEntry.AddressList[0].ToString();
return (strAddr);
}
Method二.
if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // 服务器, using proxy
{
得到真实的客户端地址
ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
}
else//如果没有使用代理服务器或者得不到客户端的ip  not using proxy or can't get the Client IP
{
得到服务端的地址
ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}

你可能感兴趣的:(获取IP)