public async Task<Location> ResolveIpAsync(string ip, CancellationToken cancellationToken = new CancellationToken()) {
            if (String.IsNullOrWhiteSpace(ip) || (!ip.Contains(".") && !ip.Contains(":")))
                return null;

            ip = ip.Trim();

            Location location;
            if (_cache.TryGet(ip, out location))
                return location;

            if (ip.IsPrivateNetwork())
                return null;

            var database = await GetDatabaseAsync(cancellationToken);
            if (database == null)
                return null;

            try {
                var city = database.City(ip);
                if (city != null && city.Location != null)
                    location = new Location { Latitude = city.Location.Latitude, Longitude = city.Location.Longitude };

                _cache.Set(ip, location);
                return location;
            } catch (Exception ex) {
                if (ex is AddressNotFoundException || ex is GeoIP2Exception) {
                    Log.Trace().Message(ex.Message).Write();
                    _cache.Set<Location>(ip, null);
                } else {
                    Log.Error().Exception(ex).Message("Unable to resolve geo location for ip: " + ip).Write();
                }

                return null;
            }
        }
Example #2
0
        public static bool TryParse(string input, out Location location) {
            location = null;
            if (String.IsNullOrWhiteSpace(input) || !input.Contains(","))
                return false;

            string[] parts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length != 2)
                return false;

            double latitude;
            if (!Double.TryParse(parts[0], out latitude))
                return false;

            double longitude;
            if (!Double.TryParse(parts[1], out longitude))
                return false;

            location = new Location { Latitude = latitude, Longitude = longitude };
            return true;
        }