C#获取客户端IP地址+获取本机外网IP

1、Web的正常获取客户端IP,一句代码即可:

Request.ServerVariables.Get("Remote_Addr").ToString();

穿过代理服务器取远程用户真实IP地址:

/// 
/// 获取客户端IP
/// 
/// 
public static string getIp()
{
	// 穿过代理服务器取远程用户真实IP地址
	string Ip = string.Empty;
	if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
	{
		if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
		{
			if (HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
				Ip = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].ToString();
			else
				if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
					Ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
				else
					Ip = "0.0.0.0";
		}
		else
			Ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
	}
	else if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
	{
		Ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
	}
	else
	{
		Ip = "0.0.0.0";
	}
	return Ip;
}

2、本机获取外网IP,可以请求外网,把ip地址获取下来

private string getIp(object sender, EventArgs e)
{
	string ip = string.Empty;

	try
	{
		string strUrl = "http://iframe.ip138.com/ic.asp"; //获得IP的网址
		Uri uri = new Uri(strUrl);
		System.Net.WebRequest wr = System.Net.WebRequest.Create(uri);
		System.IO.Stream s = wr.GetResponse().GetResponseStream();
		System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.Default);
		string all = sr.ReadToEnd(); //读取网站的数据

		int i = all.IndexOf("[") + 1;
		int en = all.IndexOf("]");
		ip = all.Substring(i, en - i);//此处获取也可用正则匹配
	}
	catch (Exception ex)
	{
		
	}
	
	return ip;
}

你可能感兴趣的:(.Net开发)