using System.Net; using System.Text; namespace Intelix.Helper; public static class IpApi { private static string _cachedIp; private static string _cachedCountryCode; private static readonly object _lock = new object(); public static string GetPublicIp() { if (!string.IsNullOrEmpty(_cachedIp)) { return _cachedIp; } lock (_lock) { if (!string.IsNullOrEmpty(_cachedIp)) { return _cachedIp; } try { using WebClient webClient = new WebClient(); string text = webClient.DownloadString("http://icanhazip.com"); if (!string.IsNullOrEmpty(text)) { _cachedIp = text.Trim(); } } catch { _cachedIp = "Request failed"; } return _cachedIp; } } public static string GetCountryCode() { if (!string.IsNullOrEmpty(_cachedCountryCode)) { return _cachedCountryCode; } lock (_lock) { if (!string.IsNullOrEmpty(_cachedCountryCode)) { return _cachedCountryCode; } try { using WebClient webClient = new WebClient(); webClient.Encoding = Encoding.UTF8; string response = webClient.DownloadString("http://ip-api.com/line/?fields=countryCode"); if (!string.IsNullOrEmpty(response)) { _cachedCountryCode = response.Trim(); } else { _cachedCountryCode = "XX"; } } catch { _cachedCountryCode = "XX"; } return _cachedCountryCode; } } }