ASP.NET中获取外网IP
答案:2 悬赏:10 手机版
解决时间 2021-05-14 13:18
- 提问者网友:几叶到寒
- 2021-05-13 12:30
在网站上获取外网IP 不是内网 我在别的地方找到的都是127.0.0.1 或者局域网的
最佳答案
- 五星知识达人网友:撞了怀
- 2021-05-13 12:45
用以下代码可以取得外网IP
private static string getIP()
{
Uri uri = new Uri(" http://www.ip.cn/getip.php?action=getip&ip_url=");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = 0;
req.CookieContainer = new System.Net.CookieContainer();
req.GetRequestStream().Write(new byte[0], 0, 0);
System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse());
System.IO.StreamReader rs = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB18030"));
string s = rs.ReadToEnd();
rs.Close();
req.Abort();
res.Close();
int start = s.IndexOf(">");
int end = s.IndexOf("</");
s = s.Substring(start + 1, end - start - 1);
return s;
}
全部回答
- 1楼网友:怀裏藏嬌
- 2021-05-13 13:00
/// 取得客户端真实IP。如果有代理则取第一个非内网地址
/// </summary>
public static string IPAddress
{
get
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (result != null && result != String.Empty)
{
//可能有代理
if (result.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式
result = null;
else
{
if (result.IndexOf(",") != -1)
{
//有“,”,估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i])
&& temparyip[i].Substring(0, 3) != "10."
&& temparyip[i].Substring(0, 7) != "192.168"
&& temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i]; //找到不是内网的地址
}
}
}
else if (IsIPAddress(result)) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP,取IP
}
}
string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
&& HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty)
? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
: HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
}
/// <summary>
/// 判断是否是IP地址格式 0.0.0.0
/// </summary>
/// <param name="str1">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIPAddress(string str1)
{
if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15)
return false;
string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str1);
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯