using System;
using System.Web;
using System.Net;
using System.Text;
public class IpLocationHandler : IHttpHandler
{
// 核心函数:传入IP,返回【国家+省+市+县】,内网直接返回 局域网IP地址
public string getIPAddress(string ip)
{
if (IsLocalIp(ip))
{
return "局域网IP地址";
}
string url = string.Format("https://ip9.com.cn/get?ip={0}", HttpUtility.UrlEncode(ip));
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
// 兼容 .NET4.0,使用数字常量开启TLS1.2,解决未能创建SSL/TLS安全通道
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 3000; //3秒超时
request.ReadWriteTimeout = 3000;
request.Method = "GET";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)";
response = (HttpWebResponse)request.GetResponse();
using (var sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string respText = sr.ReadToEnd();
string country = GetJsonValue(respText, "country");
string province = GetJsonValue(respText, "province");
string city = GetJsonValue(respText, "city");
string district = GetJsonValue(respText, "district");
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(country)) sb.Append(country);
if (!string.IsNullOrEmpty(province)) sb.Append(province);
if (!string.IsNullOrEmpty(city)) sb.Append(city);
if (!string.IsNullOrEmpty(district)) sb.Append(district);
return sb.ToString().Trim();
}
}
catch (Exception ex)
{
//调试模式:返回错误信息,上线改为 return "未知地址";
return string.Format("【ERROR】{0}", ex.ToString());
}
finally
{
if (response != null) response.Close();
if (request != null) request.Abort();
}
}
/// <summary>
/// 判断内网IP
/// </summary>
private bool IsLocalIp(string ipStr)
{
IPAddress ip;
if (!IPAddress.TryParse(ipStr, out ip))
return false;
byte[] ipBytes = ip.GetAddressBytes();
//10.0.0.0/8
if (ipBytes[0] == 10) return true;
//172.16.0.0/12
if (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) return true;
//192.168.0.0/16
if (ipBytes[0] == 192 && ipBytes[1] == 168) return true;
//回环地址
if (IPAddress.IsLoopback(ip)) return true;
return false;
}
/// <summary>
/// 简易提取JSON字段,无第三方依赖
/// </summary>
private string GetJsonValue(string json, string key)
{
string searchKey = string.Format("\"{0}\":", key);
int idx = json.IndexOf(searchKey);
if (idx < 0) return "";
int start = idx + searchKey.Length;
if (start >= json.Length) return "";
char startChar = json[start];
int end;
if (startChar == '"')
{
start++;
end = json.IndexOf('"', start);
}
else
{
end = json.IndexOf(',', start);
if (end < 0) end = json.IndexOf('}', start);
}
if (end < 0 || end > json.Length) return "";
return json.Substring(start, end - start).Trim();
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string ip = context.Request.QueryString["ip"] ?? "";
string location = getIPAddress(ip);
context.Response.Write(location);
}
public bool IsReusable
{
get { return true; }
}
}