public void HasIPAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.Traits.IPAddress, Is.EqualTo("81.2.69.160"));
     }
 }
        public GeoLocationResult GetGeoLocation(IPAddress address, NameValueCollection config)
        {
            string text = config["databaseFileName"];

            if (!string.IsNullOrEmpty(text))
            {
                maxMindDatabaseFileName = VirtualPathUtilityEx.RebasePhysicalPath(text);
                config.Remove("databaseFileName");
            }

            if (string.IsNullOrWhiteSpace(maxMindDatabaseFileName))
            {
                throw new ArgumentException("db name is not provided");
            }

            if (!System.IO.File.Exists(maxMindDatabaseFileName))
            {
                throw new ArgumentException(string.Format("db does not exist at location {0}", maxMindDatabaseFileName));
            }

            if (address.AddressFamily != AddressFamily.InterNetwork &&
                address.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return(null);
            }

            try
            {
                using (var reader = new DatabaseReader(maxMindDatabaseFileName))
                {
                    var dbResult = reader.City(address);

                    if (dbResult == null)
                    {
                        return(null);
                    }

                    GeoLocationResult result = new GeoLocationResult();
                    result.CountryCode    = dbResult.Country.IsoCode;
                    result.CountryName    = dbResult.Country.Name;
                    result.Latitude       = dbResult.Location.Latitude ?? 0;
                    result.Longitude      = dbResult.Location.Longitude ?? 0;
                    result.MetroCode      = dbResult.Location.MetroCode ?? 0;
                    result.City           = dbResult.City.Name;
                    result.PostalCode     = dbResult.Postal.Code;
                    result.CountinentCode = dbResult.Continent.Code;
                    result.Region         = dbResult?.MostSpecificSubdivision?.IsoCode;
                    result.RegionName     = dbResult.MostSpecificSubdivision?.Name;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 public void CityWithUnknownAddress_ExceptionThrown()
 {
     using (var reader = new DatabaseReader(_cityDatabaseFile))
     {
         var exception = Record.Exception(() => reader.City("10.10.10.10"));
         Assert.NotNull(exception);
         Assert.Contains("10.10.10.10 is not in the database", exception.Message);
         Assert.IsType <AddressNotFoundException>(exception);
     }
 }
Esempio n. 4
0
 public void TestLocaleList()
 {
     using (var reader = new DatabaseReader(_databaseFile, new List <string> {
         "xx", "ru", "pt-BR", "es", "en"
     }))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("Лондон"));
     }
 }
Esempio n. 5
0
 public void TestStreamConstructor()
 {
     using (StreamReader streamReader = new StreamReader(_databaseFile))
     {
         using (var reader = new DatabaseReader(streamReader.BaseStream))
         {
             var resp = reader.City("81.2.69.160");
             Assert.That(resp.City.Name, Is.EqualTo("London"));
         }
     }
 }
 public void DatabaseReaderWithStreamConstructor_ValidResponse()
 {
     using (var streamReader = File.OpenText(_cityDatabaseFile))
     {
         using (var reader = new DatabaseReader(streamReader.BaseStream))
         {
             var response = reader.City("81.2.69.160");
             Assert.Equal("London", response.City.Name);
         }
     }
 }
 public void CityWithLocaleList_ValidResponse()
 {
     using (
         var reader = new DatabaseReader(_cityDatabaseFile, new List <string> {
         "xx", "ru", "pt-BR", "es", "en"
     }))
     {
         var response = reader.City("81.2.69.160");
         Assert.Equal("Лондон", response.City.Name);
     }
 }
        public IActionResult Index()
        {
            using (var readerData = new DatabaseReader(_hostEnvironment.ContentRootPath + "\\GeoLite2-City.mmdb"))
            {
                var ipAdd = HttpContext.Connection.RemoteIpAddress;

                var cityLocation = readerData.City(ipAdd);

                return(View(cityLocation));
            }
        }
Esempio n. 9
0
 private string GetUserLocation()
 {
     using (var reader = new DatabaseReader(_hostingEnvironment.ContentRootPath + "\\GeoLite2-City_20180403" + "\\GeoLite2-City.mmdb"))
     {
         // Determine the IP Address of the request
         var ipAddress = _accessor.HttpContext.Connection.RemoteIpAddress;
         var res       = ipAddress.ToString();
         // Get the city from the IP Address
         var city = reader.City(ipAddress);
         return(city.City.Name.ToString());
     }
 }
Esempio n. 10
0
        public Region GetRegionFromIp(string ip)
        {
            var cacheKey   = $"PersonalisationGroups_GeoLocation_Region_{ip}";
            var cachedItem = RuntimeCacheHelper.GetCacheItem(cacheKey,
                                                             () =>
            {
                try
                {
                    using (var reader = new DatabaseReader(_pathToCityDb))
                    {
                        try
                        {
                            var response = reader.City(ip);
                            var region   = new Region
                            {
                                City         = response.City.Name,
                                Subdivisions = response.Subdivisions
                                               .Select(x => x.Name)
                                               .ToArray(),
                                Country = new Country
                                {
                                    Code = response.Country.IsoCode,
                                    Name = response.Country.Name,
                                }
                            };

                            return(region);
                        }
                        catch (AddressNotFoundException)
                        {
                            return(null);
                        }
                        catch (GeoIP2Exception ex)
                        {
                            if (IsInvalidIpException(ex))
                            {
                                return(null);
                            }

                            throw;
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new FileNotFoundException(
                        $"MaxMind Geolocation database required for locating visitor region from IP address not found, expected at: {_pathToCountryDb}. The path is derived from either the default ({AppConstants.DefaultGeoLocationCountryDatabasePath}) or can be configured using a relative path in an appSetting with key: \"{AppConstants.ConfigKeys.CustomGeoLocationCountryDatabasePath}\"",
                        _pathToCountryDb);
                }
            });

            return(cachedItem);
        }
Esempio n. 11
0
        //https://dev.maxmind.com/geoip/geoip2/geolite2/
        GeoIPResult InnerResolve(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = Request.UserHostAddress;
            }

            if (database == null)
            {
                database = new DatabaseReader(Server.MapPath(@"~/App_Data/GeoLite2-City.mmdb"));
            }

            var result = database.City(id.Replace("-", "."));

            if (result == null)
            {
                return(null);
            }
            else
            {
                return new GeoIPResult
                       {
                           Block = new Block()
                           {
                               isp                            = result.Traits.Isp,
                               latitude                       = result.Location.Latitude,
                               longitude                      = result.Location.Longitude,
                               postal_code                    = result.Postal.Code,
                               is_anonymous_proxy             = result.Traits.IsAnonymousProxy,
                               geoname_id                     = string.Format("{0}", result.City.GeoNameId),
                               is_satellite_provider          = result.Traits.IsSatelliteProvider,
                               registered_country_geoname_id  = string.Format("{0}", result.RegisteredCountry.GeoNameId),
                               represented_country_geoname_id = string.Format("{0}", result.RepresentedCountry.GeoNameId),
                           },
                           Location = new Location()
                           {
                               city_name              = result.City.Name,
                               continent_name         = result.Continent.Name,
                               country_name           = result.Country.Name,
                               continent_code         = result.Continent.Code,
                               country_iso_code       = result.Country.IsoCode,
                               time_zone              = result.Location.TimeZone,
                               metro_code             = string.Format("{0}", result.Location.MetroCode),
                               geoname_id             = string.Format("{0}", result.City.GeoNameId),
                               locale_code            = null,
                               subdivision_1_iso_code = result.Subdivisions.Select(x => x.IsoCode).FirstOrDefault(),
                               subdivision_1_name     = result.Subdivisions.Select(x => x.Name).FirstOrDefault(),
                               subdivision_2_iso_code = result.Subdivisions.Skip(1).Select(x => x.IsoCode).FirstOrDefault(),
                               subdivision_2_name     = result.Subdivisions.Skip(1).Select(x => x.Name).FirstOrDefault(),
                           },
                       }
            };
        }
 public void City_ValidResponse()
 {
     using (var reader = new DatabaseReader(_cityDatabaseFile))
     {
         var response = reader.City("81.2.69.160");
         Assert.Equal("London", response.City.Name);
         Assert.True(response.Country.IsInEuropeanUnion);
         Assert.Equal(100, response.Location.AccuracyRadius);
         Assert.False(response.RegisteredCountry.IsInEuropeanUnion);
         Assert.False(response.RepresentedCountry.IsInEuropeanUnion);
     }
 }
Esempio n. 13
0
        public IActionResult Index()
        {
            using (var reader = new DatabaseReader(_hostingEnvironment.ContentRootPath + "\\GeoLite2-City.mmdb"))
            {
                // Determine the IP Address of the request
                var ipAddress = HttpContext.Connection.RemoteIpAddress;

                // Get the city from the IP Address
                var city = reader.City(ipAddress);

                return(View(city));
            }
        }
 public CityResponse Get(string ip)
 {
     try
     {
         _logger.LogInformation($"Trying {ip}");
         return(_reader.City(ip));
     }
     catch (GeoIP2Exception ex)
     {
         _logger.LogError("Exception occured", ex);
         return(null);
     }
 }
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="incomingIP">The IP passed in from the IGeoLocationService Interface</param>
        /// <returns></returns>
        public async Task <GeoLocation> GetGeoLocationByIPAsync(string incomingIP)

        {
            var response = new GeoLocation();

            if (System.Net.IPAddress.TryParse(incomingIP, out var ipParseResult))
            {
                if (ipParseResult != null)
                {
                    if (ipParseResult.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        ipParseResult = Dns.GetHostEntry(ipParseResult).AddressList
                                        .First(x => x.AddressFamily == AddressFamily.InterNetwork);
                    }
                }

                var geoDB = _appSettings.Value.GeoLite2CityDB;
                response.Date      = DateTime.UtcNow.ToUniversalTime();
                response.IPAddress = ipParseResult.ToString();

                using (var reader = new DatabaseReader(geoDB))
                {
                    if (reader.TryCity(response.IPAddress, out var trycityResponse))
                    {
                        var cityResponse = reader.City(response.IPAddress);
                        response.City           = cityResponse.City.ToString();
                        response.TimeZone       = cityResponse.Location.TimeZone.ToString();
                        response.Continent      = cityResponse.Continent.ToString();
                        response.Country        = cityResponse.Country.ToString();
                        response.IPFoundInGeoDB = true;
                        response.Message        = (response.IPAddress + " found in the GeoDB");
                    }
                    else
                    {
                        response.IPFoundInGeoDB = false;
                        _logger.LogWarning(response.IPAddress + " not found in the GeoDB");
                        response.Message = (response.IPAddress + " not found in the GeoDB");
                    }
                }
                return(await Task.FromResult(response));
            }
            else
            {
                response.IPFoundInGeoDB = false;
                _logger.LogWarning(incomingIP + " Unable to Parse");
                response.Message = (incomingIP + " Unable to Parse");
                return(await Task.FromResult(response));
            }
        }
Esempio n. 16
0
        public async Task <JsonResult> GetCity(string ip = null)
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                return(new JsonResult(new ResponseModel(null, "IP address should not be NULL")));
            }

            if (IPAddress.TryParse(ip, out var address))
            {
                if (address.AddressFamily != AddressFamily.InterNetwork)
                {
                    return(new JsonResult(new ResponseModel(null, "Ip address invalidate")));
                }

                try
                {
                    var response = _databaseReader.City(address);
                    if (response == null)
                    {
                        return(new JsonResult(new ResponseModel(null, "Data not found")));
                    }

                    var existIps = await _ipV4ClientsRepository
                                   .FetchAsync(new IpV4ClientFilter(x => x.IpV4.Equals(ip)))
                                   .ConfigureAwait(continueOnCapturedContext: false);

                    if (existIps.Count > 0)
                    {
                        return(new JsonResult(new ResponseModel(ModelFactory.CreateIpClient(existIps[0]))));
                    }

                    var ipAdded = await AddIpAddressAsync(address, response).ConfigureAwait(continueOnCapturedContext: false);

                    if (ipAdded != null)
                    {
                        return(new JsonResult(new ResponseModel(ModelFactory.CreateIpClient(ipAdded))));
                    }
                }
                catch (Exception exc)
                {
                    return(new JsonResult(new ResponseModel(null, exc.ToString())));
                }

                return(new JsonResult(new ResponseModel(null, "Save to database failde")));
            }

            return(new JsonResult(new ResponseModel(null, "Ip address invalidate")));
        }
Esempio n. 17
0
        public Region GetRegionFromIp(string ip)
        {
            var cacheKey   = $"PersonalisationGroups_GeoLocation_Region_{ip}";
            var cachedItem = ApplicationContext.Current.ApplicationCache.RuntimeCache
                             .GetCacheItem(cacheKey,
                                           () =>
            {
                try
                {
                    using (var reader = new DatabaseReader(_pathToCityDb))
                    {
                        try
                        {
                            var response = reader.City(ip);
                            var country  = new Region
                            {
                                City         = response.City.Name,
                                Subdivisions = response.Subdivisions
                                               .Select(x => x.Name)
                                               .ToArray(),
                                Country = new Country
                                {
                                    Code = response.Country.IsoCode,
                                    Name = response.Country.Name,
                                }
                            };

                            HttpRuntime.Cache.Insert(cacheKey, country, null,
                                                     Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);

                            return(country);
                        }
                        catch (AddressNotFoundException)
                        {
                            return(string.Empty);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new FileNotFoundException(
                        $"MaxMind Geolocation database required for locating visitor region from IP address not found, expected at: {_pathToCountryDb}. The path is derived from either the default ({AppConstants.DefaultGeoLocationCountryDatabasePath}) or can be configured using a relative path in an appSetting with key: \"{AppConstants.ConfigKeys.CustomGeoLocationCountryDatabasePath}\"",
                        _pathToCountryDb);
                }
            });

            return(cachedItem as Region);
        }
        /// <summary>
        /// Map the given IP as a location
        /// </summary>
        /// <returns></returns>
        public static GeoLocation MapIP(IPAddress ip)
        {
            try
            {
                var maxMindResult = _maxMindsDatabaseReader.City(ip);

                // Make sure we don't pass null values as the results are returned as a 'double?'
                var longitude = maxMindResult.Location.Longitude.HasValue ? maxMindResult.Location.Longitude.Value : 0;
                var latitude  = maxMindResult.Location.Latitude.HasValue ? maxMindResult.Location.Latitude.Value : 0;

                return(new GeoLocation(maxMindResult.Country.IsoCode, longitude, latitude));
            }
            catch {
                return(new GeoLocation("", 0, 0));
            }
        }
Esempio n. 19
0
        public static GeoIPInfo GetIPInfo(DatabaseReader dbReader, string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return(null);
            }
            else if (Utilities.IsLocalIP(ip))
            {
                return new GeoIPInfo()
                       {
                           IP = ip, IsLocal = true
                       }
            }
            ;

            try
            {
                var info = dbReader.City(ip);

                return(new GeoIPInfo()
                {
                    IP = ip,
                    ISP = info.Traits.Isp,
                    Country = info.Country.IsoCode,
                    CountryName = info.Country.Name,
                    Region = info.Subdivisions != null && info.Subdivisions.Count != 0 ? info.Subdivisions[0].IsoCode : "",
                    RegionName = info.Subdivisions != null && info.Subdivisions.Count != 0 ? info.Subdivisions[0].Name : "",
                    City = info.City.Name,
                    ZIP = info.Postal.Code,
                    Latitude = info.Location.Latitude,
                    Longitude = info.Location.Longitude,
                    IsProxy = info.Traits.IsAnonymousProxy
                });
            }
            catch (AddressNotFoundException anfex)
            {
                // TO DO: Log Exception
                return(null);
            }
            catch (Exception ex)
            {
                // TO DO: Log Exception
                return(null);
            }
        }
    }
Esempio n. 20
0
        private OfficeLocation GetClientLocationByIp()
        {
            OfficeLocation retval = new OfficeLocation();

            try
            {
                using (var reader = new DatabaseReader("GeoLite2Db/GeoLite2-City.mmdb"))
                {
                    // Replace "City" with the appropriate method for your database, e.g.,
                    // "Country".
                    string clientIp = Request.UserHostAddress;
                    var    city     = reader.City(clientIp);

                    Console.WriteLine(city.Country.IsoCode);                 // 'US'
                    Console.WriteLine(city.Country.Name);                    // 'United States'

                    Console.WriteLine(city.MostSpecificSubdivision.Name);    // 'Minnesota'
                    Console.WriteLine(city.MostSpecificSubdivision.IsoCode); // 'MN'

                    Console.WriteLine(city.City.Name);                       // 'Minneapolis'
                    retval.Name = city.City.Name;
                    Console.WriteLine(city.Postal.Code);                     // '55455'

                    Console.WriteLine(city.Location.Latitude);               // 44.9733
                    Console.WriteLine(city.Location.Longitude);              // -93.2323

                    retval.LocationX = city.Location.Latitude.HasValue ? city.Location.Latitude.Value : 59.3252315;
                    retval.LocationY = city.Location.Longitude.HasValue ? city.Location.Longitude.Value : 18.0599355;
                    if (!city.Location.Latitude.HasValue || !city.Location.Longitude.HasValue)
                    {
                        retval.Name      = "Osäker position";
                        retval.LocationX = 59.3252315;
                        retval.LocationY = 18.0599355;
                    }
                }
            }
            catch
            {
                retval.Name      = "Osäker position";
                retval.LocationX = 59.3252315;
                retval.LocationY = 18.0599355;
            }

            return(retval);
        }
Esempio n. 21
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log, ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // parse query parameter
            string ip = req.GetQueryNameValuePairs()
                        .FirstOrDefault(q => string.Compare(q.Key, "ip", true) == 0)
                        .Value;
            string mmdbPath = System.IO.Path.Combine(context.FunctionAppDirectory, Environment.GetEnvironmentVariable("mmdbFilePath"));

            log.Info(mmdbPath);
            var reader   = new DatabaseReader(mmdbPath);
            var response = reader.City(ip);

            return(ip == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass IP Address 81.2.69.160")
                : req.CreateResponse(HttpStatusCode.OK, "Response Is" + response));
        }
Esempio n. 22
0
        public static string GetCountryLocal(string ip)
        {
            if (string.IsNullOrEmpty(ip)) return string.Empty;

            try
            {
                using (var reader = new DatabaseReader(@"IPDatabase\GeoLite2-City.mmdb"))
                {

                    var city = reader.City(ip);
                    return city.Country.Name;
                }
            }
            catch(Exception e)
            {
                return string.Empty;
            }
        }
        public async Task <Location> Get(string ip)
        {
            Location location = new Location();

            using (var reader = new DatabaseReader("./Utils/GeoLite2-City.mmdb"))
            {
                // Replace "City" with the appropriate method for your database, e.g.,
                // "Country".
                var city = reader.City(ip);
                if (city.Location.Latitude != null && city.Location.Longitude != null)
                {
                    location = new Location((double)city.Location.Latitude, (double)city.Location.Longitude);
                    Console.Out.WriteLine(city.City);
                }
            }

            return(location);
        }
Esempio n. 24
0

        
Esempio n. 25
0
        public override WhoIsInformation Resolve(IPAddress ip)
        {
            var whoIsInformation = new WhoIsInformation();

            using (var reader = new DatabaseReader(HostingEnvironment.MapPath(_databasePath)))
            {
                var city = reader.City(ip);

                if (city != null)
                {
                    Sitecore.Diagnostics.Log.Info("GeoIPFallback: current location was resolved by local MaxMind database.", this);

                    whoIsInformation.Country = city.Country.IsoCode;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Country: " + whoIsInformation.Country, this);

                    whoIsInformation.City = city.City.Name;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: City: " + whoIsInformation.City, this);

                    whoIsInformation.PostalCode = city.Postal.Code;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Postal Code: " + whoIsInformation.PostalCode, this);

                    whoIsInformation.Latitude = city.Location.Latitude;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Latitude: " + whoIsInformation.Latitude, this);

                    whoIsInformation.Longitude = city.Location.Longitude;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Longitude: " + whoIsInformation.Longitude, this);

                    whoIsInformation.MetroCode = city.MostSpecificSubdivision.Name;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Metro Code: " + whoIsInformation.MetroCode, this);

                    whoIsInformation.AreaCode = city.MostSpecificSubdivision.IsoCode;
                    Sitecore.Diagnostics.Log.Debug("GeoIPFallback: Area Code: " + whoIsInformation.AreaCode, this);
                }
                else
                {
                    Sitecore.Diagnostics.Log.Info(
                        "GeoIPFallback: current location was not resolved by local MaxMind database.", this);
                    whoIsInformation.BusinessName = "Not Available";
                }
            }

            return(whoIsInformation);
        }
Esempio n. 26
0
        private void GetSSHinfo(string _ip)
        {
            using (var reader = new DatabaseReader("GeoLite2-City.mmdb"))
            {
                var city = reader.City(_ip);
                if (city.Location.TimeZone != null)
                {
                    var _windowstimezone = IanaToWindows(city.Location.TimeZone);
                    tzi    = TimeZoneInfo.FindSystemTimeZoneById(_windowstimezone);
                    offset = tzi.GetUtcOffset(DateTime.Now);
                    if (cbChangetimezone.Checked && _windowstimezone != null)
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.FileName    = "TZUTIL.exe";
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.Arguments   = "/s \"" + _windowstimezone + "\"";
                        try
                        {
                            using (Process exeProcess = Process.Start(startInfo))
                            {
                                exeProcess.WaitForExit();
                            }
                        }
                        catch
                        {
                            // Log error.
                        }
                        this.Invoke((MethodInvoker) delegate() { lblTimezone.Text = offset.Hours + ":" + offset.Minutes; });
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate() { lblTimezone.Text = "Unknow"; });
                    }
                }
                else
                {
                    this.Invoke((MethodInvoker) delegate() { lblTimezone.Text = "Unknow"; });
                }
                this.Invoke((MethodInvoker) delegate() { txtSSHinfo.Text = city.Country.Name + " | " + city.MostSpecificSubdivision.Name + " (" + city.MostSpecificSubdivision.IsoCode + ") | " + city.City.Name + " | " + city.Postal.Code; });

                //Console.WriteLine(city.Country.IsoCode); // 'US'
            }
        }
Esempio n. 27
0

        
Esempio n. 28
0
        private void UpdateDatabase(string geo2IPDbPath)
        {
            _logger.LogInformation("Updating database from {0}.", geo2IPDbPath);

            using (var context = _serviceProvider.GetRequiredService <IDataContext>())
                using (var reader = new DatabaseReader(geo2IPDbPath))
                {
                    int count      = context.IPLocations.All.Count();
                    int batchSize  = 100;
                    int batchCount = count / batchSize + (count % batchSize > 0 ? 1 : 0);

                    var locations = context.IPLocations.All.Take(batchCount).ToList();

                    for (int i = 0; i < batchCount; i++)
                    {
                        var nextLocations = context.IPLocations.All.Skip((i + 1) * batchCount).Take(batchCount).ToListAsync();

                        foreach (var location in locations)
                        {
                            try
                            {
                                var info = reader.City(location.IP);
                                location.City      = info.City.Name;
                                location.Country   = info.Country.Name;
                                location.Continent = info.Continent.Name;
                                location.Latitude  = info.Location.Latitude;
                                location.Longitude = info.Location.Longitude;
                            }
                            catch (AddressNotFoundException exc)
                            {
                                _logger.LogError(exc, "IP: {0}", location.IP);
                            }
                        }

                        locations = nextLocations.Result;
                        context.SaveChanges();

                        _logger.LogInformation("Updated {0} of {1} batches", i + 1, batchCount);
                    }
                }

            _logger.LogInformation("Update complete.");
        }
Esempio n. 29
0
        public async Task <IActionResult> CreateLog()
        {
            // get visitor geolocation info
            using (var reader = new DatabaseReader(_hostingEnvironment.ContentRootPath + "\\Data\\GeoLog\\GeoLite2-City.mmdb"))
            {
                // for  local dev test Determine the IP Address of the request
                // var ipAddress = "180.255.44.125";

                // get user/visitor ip address
                var ipAddress = HttpContext.Connection.RemoteIpAddress;

                // Get the city from the IP Address
                var log = reader.City(ipAddress);

                // ensure logging is done once a day only. Compares ip address and datelogged to current date
                // var IPDateExist = (_context.Logs.Where(g => g.IPAddress == ipAddress.ToString() && g.DateLogged.Date == DateTime.Now.Date).Count() > 0) ? true : false;
                var IPDateExist = _repo.IPDateExist(ipAddress.ToString());

                // when log does not exist, create or add log
                if (!IPDateExist)
                {
                    //save or log visitor info
                    Log geoLog = new Log();
                    geoLog.IPAddress  = ipAddress.ToString();
                    geoLog.City       = log.City.ToString();
                    geoLog.Country    = log.Country.ToString();
                    geoLog.Timezone   = log.Location.TimeZone;
                    geoLog.DateLogged = DateTime.Now;

                    var newLog = _mapper.Map <Log>(geoLog);
                    _repo.Add <Log>(newLog);

                    if (await _repo.SaveAll())
                    {
                        return(Ok(newLog));
                    }
                    throw new Exception("Log creation failed on save.");
                }

                return(Ok("ip already exist, no new log was created."));
            }
        }
Esempio n. 30
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(" , "));
        }
Esempio n. 31
0
        public string GetCountryLocal(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return(string.Empty);
            }

            try
            {
                using (var reader = new DatabaseReader(@"IPDatabase\GeoLite2-City.mmdb"))
                {
                    var city = reader.City(ip);
                    return(city.Country.Name);
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Esempio n. 32
0
        public HttpResponseMessage Get()
        {
            try
            {
                MapDTO dto = new MapDTO()
                {
                    latitude  = "37.09024",
                    longitude = "-95.712891"
                };

                string ip_address = this.Request.GetIPAddress();

                //ip_address = "104.185.202.20"; // for testing on localhost, should resolve to Atlanta, GA...

                using (var objGeoIP2DB = new DatabaseReader(string.Concat(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\GeoIP2-City.mmdb")))
                {
                    try
                    {
                        var objGeoIP2 = objGeoIP2DB.City(ip_address);
                        if (objGeoIP2 != null)
                        {
                            dto.latitude  = objGeoIP2.Location.Latitude.ToString();
                            dto.longitude = objGeoIP2.Location.Longitude.ToString();
                        }
                    }
                    catch
                    {
                        // IP address cannot be resolved
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.OK, dto));
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Esempio n. 33
0
 public void TestDefaultLocale()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
Esempio n. 34
0
 public void UnknownAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         reader.City("10.10.10.10");
     }
 }
Esempio n. 35
0
 public void TestStreamConstructor()
 {
     using (StreamReader streamReader = new StreamReader(_databaseFile))
     {
         using (var reader = new DatabaseReader(streamReader.BaseStream))
         {
             var resp = reader.City("81.2.69.160");
             Assert.That(resp.City.Name, Is.EqualTo("London"));
         }
     }
 }
Esempio n. 36
0
 public void TestMemoryMode()
 {
     using (var reader = new DatabaseReader(_databaseFile, FileAccessMode.Memory))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
Esempio n. 37
0
 public void TestWithIPAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.City(IPAddress.Parse("81.2.69.160"));
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
Esempio n. 38
0
 public void TestLocaleList()
 {
     using (var reader = new DatabaseReader(_databaseFile, new List<string> { "xx", "ru", "pt-BR", "es", "en" }))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("Лондон"));
     }
 }