Skip to content

Commit

Permalink
feat: ip service for retrieving external ip from providers
Browse files Browse the repository at this point in the history
  • Loading branch information
alperensert committed Apr 9, 2024
1 parent 9276377 commit ee647df
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

Expand Down
6 changes: 6 additions & 0 deletions src/CloudflareDnsync.Services/IIPService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace CloudflareDnsync.Services;

public interface IIPService
{
Task<string> GetPublicIpAsync(CancellationToken cancellationToken = default);
}
32 changes: 32 additions & 0 deletions src/CloudflareDnsync.Services/IPService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Logging;

namespace CloudflareDnsync.Services;

public sealed class IPService(ILogger<IPService> 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<string> 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");
}
}

0 comments on commit ee647df

Please sign in to comment.