From ee647dfd19fa02aeb898a652c14f4fec512a16dc Mon Sep 17 00:00:00 2001 From: alperensert <63921520+alperensert@users.noreply.github.com> Date: Tue, 9 Apr 2024 12:36:37 +0300 Subject: [PATCH] feat: ip service for retrieving external ip from providers --- .../CloudflareDnsync.Services.csproj | 1 + src/CloudflareDnsync.Services/IIPService.cs | 6 ++++ src/CloudflareDnsync.Services/IPService.cs | 32 +++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 src/CloudflareDnsync.Services/IIPService.cs create mode 100644 src/CloudflareDnsync.Services/IPService.cs diff --git a/src/CloudflareDnsync.Services/CloudflareDnsync.Services.csproj b/src/CloudflareDnsync.Services/CloudflareDnsync.Services.csproj index d0cf0a5..ce117d6 100644 --- a/src/CloudflareDnsync.Services/CloudflareDnsync.Services.csproj +++ b/src/CloudflareDnsync.Services/CloudflareDnsync.Services.csproj @@ -5,6 +5,7 @@ + diff --git a/src/CloudflareDnsync.Services/IIPService.cs b/src/CloudflareDnsync.Services/IIPService.cs new file mode 100644 index 0000000..4ad031f --- /dev/null +++ b/src/CloudflareDnsync.Services/IIPService.cs @@ -0,0 +1,6 @@ +namespace CloudflareDnsync.Services; + +public interface IIPService +{ + Task GetPublicIpAsync(CancellationToken cancellationToken = default); +} diff --git a/src/CloudflareDnsync.Services/IPService.cs b/src/CloudflareDnsync.Services/IPService.cs new file mode 100644 index 0000000..3921c9e --- /dev/null +++ b/src/CloudflareDnsync.Services/IPService.cs @@ -0,0 +1,32 @@ +using Microsoft.Extensions.Logging; + +namespace CloudflareDnsync.Services; + +public sealed class IPService(ILogger logger) : IIPService +{ + private readonly Uri[] _providers = [ + new Uri("https://api.ipify.org"), + new Uri("https://icanhazip.com"), + new Uri("https://ifconfig.me"), + new Uri("https://ident.me"), + ]; + + public async Task GetPublicIpAsync(CancellationToken cancellationToken = default) + { + foreach (var provider in _providers) + { + try + { + using var client = new HttpClient(); + var response = await client.GetAsync(provider, cancellationToken); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStringAsync(cancellationToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to retrieve public IP from {Provider}", provider.Host); + } + } + throw new Exception("Failed to retrieve public IP from all providers"); + } +}