コード例 #1
0
        public void MemorySearchTestForChinese()
        {
            const int    cityId = 2163;
            const string region = "中国|0|广东省|深圳市|鹏博士";

            var result = _dbSearcher.MemorySearch("101.105.35.57");

            Assert.AreEqual(result.CityID, cityId);
            Assert.AreEqual(result.Region, region);
        }
コード例 #2
0
ファイル: SearchTest.cs プロジェクト: lionsoul2014/ip2region
        public void Search_Test()
        {
            string memResult              = _search.MemorySearch("223.104.246.20").Region;
            string binarySearchResult     = _search.BinarySearch("223.104.246.20").Region;
            string binaryTreeSearchResult = _search.BtreeSearch("223.104.246.20").Region;

            Assert.NotNull(memResult);
            Assert.NotNull(binarySearchResult);
            Assert.NotNull(binaryTreeSearchResult);

            Assert.Equal(memResult, binarySearchResult);
            Assert.Equal(binaryTreeSearchResult, memResult);
        }
コード例 #3
0
 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();
     }
 }
コード例 #4
0
 /// <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);
     }
 }
コード例 #5
0
        public static (string location, string network) GetIPLocation(this IPAddress ip)
        {
            switch (ip.AddressFamily)
            {
            case AddressFamily.InterNetwork when ip.IsPrivateIP():
            case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
                return("内网", "内网IP");

            case AddressFamily.InterNetwork:
                var parts    = IPSearcher.MemorySearch(ip.ToString()).Region.Split('|');
                var network  = parts[^ 1] == "0" ? "未知" : parts[^ 1];
コード例 #6
0
ファイル: Test.cs プロジェクト: chaosact/IP2Region.Standard
 public DataBlock OldMemorySearch(uint ip)
 {
     try
     {
         return(_DbSearcher.MemorySearch(ip));
     }
     catch (Exception ex)
     {
         Console.WriteLine($"BtreeSearch:{ip} {ex}");
         throw ex;
     }
 }
コード例 #7
0
        public IpInfo Search(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                throw new ArgumentException(nameof(ip));
            }

            var region = _search.MemorySearch(ip).Region;
            var ipinfo = RegionStrToIpInfo(region);

            ipinfo.IpAddress = ip;
            return(ipinfo);
        }
コード例 #8
0
        /// <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);
        }
コード例 #9
0
        public static (string location, string network) GetIPLocation(this IPAddress ip)
        {
            switch (ip.AddressFamily)
            {
            case AddressFamily.InterNetwork when ip.IsPrivateIP():
            case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
                return("内网", "内网IP");

            case AddressFamily.InterNetworkV6 when ip.IsIPv4MappedToIPv6:
                ip = ip.MapToIPv4();
                goto case AddressFamily.InterNetwork;

            case AddressFamily.InterNetwork:
                var parts = IPSearcher.MemorySearch(ip.ToString())?.Region.Split('|');
                if (parts != null)
                {
                    var asn      = GetIPAsn(ip);
                    var network  = parts[^ 1] == "0" ? asn.AutonomousSystemOrganization : parts[^ 1];
コード例 #10
0
        public static (string location, string network) GetIPLocation(this IPAddress ip)
        {
            switch (ip.AddressFamily)
            {
            case AddressFamily.InterNetwork when ip.IsPrivateIP():
            case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
                return("内网", "内网IP");

            case AddressFamily.InterNetworkV6 when ip.IsIPv4MappedToIPv6:
                ip = ip.MapToIPv4();
                goto case AddressFamily.InterNetwork;

            case AddressFamily.InterNetwork:
                var parts = IPSearcher.MemorySearch(ip.ToString())?.Region.Split('|');
                if (parts != null)
                {
                    var asn = Policy <AsnResponse> .Handle <AddressNotFoundException>().Fallback(new AsnResponse()).Execute(() => MaxmindAsnReader.Asn(ip));

                    var network  = parts[^ 1] == "0" ? asn.AutonomousSystemOrganization : parts[^ 1];
コード例 #11
0
        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));
        }
コード例 #12
0
        public static string GetIPLocation(this string ips)
        {
            return(ips.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s =>
            {
                var ip = IPAddress.Parse(s.Trim());
                switch (ip.AddressFamily)
                {
                case AddressFamily.InterNetwork when ip.IsPrivateIP():
                case AddressFamily.InterNetworkV6 when ip.IsPrivateIP():
                    return "内网IP";

                case AddressFamily.InterNetwork:
                    return IPSearcher.MemorySearch(ip.ToString())?.Region;

                default:
                    var response = MaxmindReader.City(ip);
                    return response.Country.Names.GetValueOrDefault("zh-CN") + response.City.Names.GetValueOrDefault("zh-CN");
                }
            }).Join(" , "));
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: zhongyoub/ip2region
        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");
        }
コード例 #14
0
ファイル: ExceptionTest.cs プロジェクト: asiacny/ip2region
        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);
            }
        }
コード例 #15
0
        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);
        }
コード例 #16
0
ファイル: HandleListView.cs プロジェクト: qwqdanchun/DcRat
        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 { }
        }