艾瑪,這兩天為了整這個ip 真的可謂無所不用其極。
在網上查閱了各種資料,其實我想實現的功能很簡單
就像百度

直接看到自己的出口ip
奈何查了許多資料,都沒有適合的解決辦法。
靈機一動,我是不是可以訪問百度的api呢?
於是點擊了上面的Ip地址查詢,跳轉到了 http://www.ip138.com/
然后我試着在顯示Ip的地方,查看元素
驚喜來了
原來它是套了一個iframe
把 iframe 的地址那出來 http://2018.ip138.com/ic.asp
直接返回ip地址和所在地。

接着對返回數據進行解析
public static string getExternalIp()
{
try
{
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.Default;
string response = client.DownloadString("http://2018.ip138.com/ic.asp");
string myReg = @"<center>([\s\S]+?)<\/center>";
Match mc = Regex.Match(response, myReg, RegexOptions.Singleline);
if (mc.Success && mc.Groups.Count > 1)
{
var resStart = mc.Groups[1].Value.IndexOf('[');
var resEnd = mc.Groups[1].Value.IndexOf(']');
var resSub = mc.Groups[1].Value.Substring(resStart + 1, resEnd - resStart - 1);
response = resSub;
return response;
}
else
{
return "0.0.0.0";
}
}
catch (Exception)
{
return "0.0.0.0";
}
}
完美,是不是大功告成?
可是在測試的途中發現有時候依然會失敗,返回數據為 "0.0.0.0"
於是我又加了一個定時器
GetAddressIP();
if (!this.lblIp.Content.ToString().Equals("0.0.0.0"))
{
selectIp.Stop();
}
每一秒去取一次Ip,直到取到為止
當然我覺得這都不是最好的辦法
可是轉念一想,為什么我們不自己寫一個獲取請求者的Ip的接口呢?
在這里我得感謝一個人
多虧有了這位大哥的幫忙,才讓我得已在 .net core api 下面成功拿到了請求者的Ip
初始化時
services.AddMvc();
services.Configure<IISOptions>(options =>
{
options.ForwardClientCertificate = false;
});
然后接口這里
private IHttpContextAccessor _accessor;
public Controller(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
[HttpPost, Route("GetIp")]
public ActionResult<string> GetIp()
{
var ip = _accessor.HttpContext.Connection.RemoteIpAddress;
return ip.ToString();
}
因為我是.net core 的緣故。所以用到了IHttpContextAccessor
我想如果是普通的api 應該直接就可以用Request 吧,就像老六大哥說的那樣~
