-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: ip service for retrieving external ip from providers
- Loading branch information
1 parent
9276377
commit ee647df
Showing
3 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
} | ||
} |