static CountryResponse GeoLocate_GetCountry(System.Net.IPAddress ipaddress) { using (var mm = new MaxMind.GeoIP2.DatabaseReader(GEOLOCATION_COUNTRY_DB_FILE)) { var responce = mm.Country(ipaddress); return(responce); } }
public async Task <string> FormatCountry(string endPoint) { var cacheKey = $".CountryInfo:{endPoint}"; var cachedString = await m_cache.GetStringAsync(cacheKey); if (cachedString != null) { return(cachedString); } string cc = "us"; var geoLitePath = Path.Combine(Startup.RootPath, "GeoLite2-Country.mmdb"); if (File.Exists(geoLitePath)) { try { if (ms_mmdbReader == null) { ms_mmdbReader = new MaxMind.GeoIP2.DatabaseReader(geoLitePath); } var country = ms_mmdbReader.Country(endPoint.Replace("[", "").Replace("]", "").Replace("::ffff:", "")); cc = country.Country.IsoCode.ToLowerInvariant(); } catch {} } else { try { var response = await ms_httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, $"https://freegeoip.app/json/{endPoint.Replace("[", "").Replace("]", "")}")); if (response.IsSuccessStatusCode) { var obj = JObject.Parse(await response.Content.ReadAsStringAsync()); cc = obj.Value <string>("country_code").ToLowerInvariant(); if (cc == "") { cc = "us"; } } } catch {} } await m_cache.SetStringAsync(cacheKey, cc, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) }); return(cc); }
/// <summary> /// Checks the country to which the ip's belong to and determines whether or not access is denied or allowed /// </summary> /// <param name="ipAddressesToCheck">The ip addresses to check</param> /// <param name="resultMessage">An explanation of the result</param> /// <returns>True if access is allowed. False otherwise</returns> /// <remarks>All IP addresses must be allowed for the request to be allowed</remarks> public bool Allowed(List <System.Net.IPAddress> ipAddressesToCheck, out string resultMessage) { if (ipAddressesToCheck == null || ipAddressesToCheck.Count == 0) { resultMessage = "No valid IP found in request"; return(false); } using (var reader = new MaxMind.GeoIP2.DatabaseReader(geoIpFilepath, MaxMind.Db.FileAccessMode.MemoryMapped)) { //sanity check if (reader == null) { resultMessage = "IP check failed"; return(true); } foreach (System.Net.IPAddress ipAddress in ipAddressesToCheck) { //first check if the IP is a private ip. It turns out that proxy servers put private ip addresses in the X_FORWARDED_FOR header. //we won't base our geoblocking on private ip addresses if (IPUtilities.IsPrivateIpAddress(ipAddress)) { continue; } //next check the exception rules bool matchedOnExceptionRule = false; bool allowedByExceptionRule = false; foreach (ExceptionRule exceptionRule in exceptionRules) { if (IpAddressMatchesExceptionRule(ipAddress, exceptionRule)) { matchedOnExceptionRule = true; if (exceptionRule.AllowedMode) { allowedByExceptionRule = true; } else { allowedByExceptionRule = false; //one IP denied = deny access alltogether break; } } } if (matchedOnExceptionRule) { if (allowedByExceptionRule) { //IP found that matches an allow exception rule, don't check the country //We continue if verifyAll is specified, because another IP could be denied if (verifyAll) { continue; } else { break; } } else { //IP found that matches a deny exception rule, deny access immediately resultMessage = "Blocked IP: [" + ipAddress.ToString() + "]"; return(false); } } if (reader.Metadata.DatabaseType.ToLower().IndexOf("country") == -1) { throw new System.InvalidOperationException("This is not a GeoLite2-Country or GeoIP2-Country database"); } string countryCode = string.Empty; //not found in exception rule, so base access rights on the country try { MaxMind.GeoIP2.Responses.CountryResponse countryResponse = reader.Country(ipAddress); countryCode = !string.IsNullOrEmpty(countryResponse.Country.IsoCode) ? countryResponse.Country.IsoCode : !string.IsNullOrEmpty(countryResponse.RegisteredCountry.IsoCode) ? countryResponse.RegisteredCountry.IsoCode : string.Empty; } catch (MaxMind.GeoIP2.Exceptions.AddressNotFoundException) { } catch (MaxMind.GeoIP2.Exceptions.PermissionRequiredException) { } catch (MaxMind.GeoIP2.Exceptions.GeoIP2Exception) { } finally { if (string.IsNullOrEmpty(countryCode)) { countryCode = "--"; } } bool selected = CountryCodeSelected(countryCode); bool allowed = (selected == allowedMode); /* * allowedmode selected allowed * 1 1 1 * 1 0 0 * 0 1 0 * 0 0 1 */ if (!allowed) { resultMessage = "Blocked IP: [" + ipAddress.ToString() + "] from [" + countryCode + "]"; return(false); } else { // If a proxy in HTTP_X_FORWARDED_FOR should be ignored if previous checked ip matches previous found country or exceptionRule if (!verifyAll) { break; } } } } resultMessage = "None"; return(true); }
/// <summary> /// 取 IP 国家 ISO 代码 /// </summary> /// <param name="ip">IP</param> /// <returns></returns> public static string GetCountryISOCode(IPAddress ip) { return(Database.Country(ip).Country.IsoCode); }