C#获取访问者ip和获取本机ip地址

C#获取访问者ip和获取本机ip地址

获取访问者ip:

string userIP;
// HttpRequest Request = HttpContext.Current.Request;  
HttpRequest Request = System.Web.HttpContext.Current.Request; // 如果使用代理,获取真实IP  
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
    userIP = Request.ServerVariables["REMOTE_ADDR"];
else
    userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (userIP == null || userIP == "")
    userIP = Request.UserHostAddress;
return userIP;

获取本机外网ip:

//获取本机外网ip的url
string getIpUrl = "http://www.ipip.net/ip.html";//网上获取ip地址的网站
string tempip = "";
WebRequest wr = WebRequest.Create(getIpUrl);
Stream s = wr.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
string all = sr.ReadToEnd(); //读取网站的数据
//解析出需要的数据
int start = all.IndexOf("您的当前IP: ");
int end = all.IndexOf("");
tempip = all.Substring(start, end - start).Replace("您的当前IP: ", "");
sr.Close();
s.Close();

 

posted @ 2016-08-29 20:47 青衫仗剑 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(C#获取访问者ip和获取本机ip地址)