Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ApiClient
- {
- private static readonly HttpClient _httpClient;
- private string ServerAddress => IP;
- private string Address => pathService.OdbcClientAddress;
- private readonly IPathService pathService; // ignore this
- public string IP => pathService.OdbcClientIP;
- public static readonly SemaphoreSlim MDnsResolveLock = new SemaphoreSlim(1, 1);
- public ApiClient(IPathService pathService)
- {
- this.pathService = pathService;
- }
- static ApiClient()
- {
- byte[] trustedCertBytes;
- var assembly = Assembly.GetExecutingAssembly();
- using (var stream = assembly.GetManifestResourceStream("MyApp.cert.cer")!)
- {
- trustedCertBytes = new byte[stream.Length];
- stream.ReadExactly(trustedCertBytes);
- }
- // Use certificate pinning
- var handler = new HttpClientHandler
- {
- ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
- {
- return cert!.GetRawCertData().SequenceEqual(trustedCertBytes);
- }
- };
- _httpClient = new HttpClient(handler);
- _httpClient.Timeout = TimeSpan.FromSeconds(20);
- _httpClient.DefaultRequestHeaders.Add("x-api-key", Constants.API_KEY);
- }
- public async Task<Result> GetIP()
- {
- await MDnsResolveLock.WaitAsync();
- try
- {
- if (OperatingSystem.IsWindows())
- {
- if (Address.Any(char.IsLetter))
- pathService.OdbcClientIP = Address + ".local";
- else
- pathService.OdbcClientIP = Address;
- pathService.MDnsResolved = true; // MDnsResolved just checks if it was already resolved, otherwise it skips this GetIP method. When there is an exception then it marks it as false
- return Result.Success; // Self-made class Result
- }
- if (pathService.MDnsResolved) return Result.Success;
- if (Address.Any(char.IsLetter))
- { // The address was written as a computer name instead of an IP, so look for IP (Android can't reoslve on its own)
- for (int i = 0; i < 5; i++)
- {
- string? address = await ResolveMdnsHostAsync(Address);
- if (address != null)
- {
- pathService.OdbcClientIP = address;
- pathService.MDnsResolved = true;
- break;
- }
- await Task.Delay(200);
- }
- }
- else
- {
- pathService.OdbcClientIP = Address;
- pathService.MDnsResolved = true;
- }
- return Result.Success;
- }
- catch (Exception ex)
- {
- pathService.MDnsResolved = false;
- return Result.Failure(ex.Message);
- }
- finally
- {
- MDnsResolveLock.Release();
- }
- }
- private static async Task<string?> ResolveMdnsHostAsync(string hostname)
- {
- if (hostname.EndsWith(".local", StringComparison.OrdinalIgnoreCase))
- hostname = hostname.Substring(0, hostname.Length - 6);
- // Search all networks hosts using mDNS
- var results = await ZeroconfResolver.ResolveAsync("_https._tcp.local.");
- // Find host by hostname
- var host = results.FirstOrDefault(h =>
- h.DisplayName.Equals(hostname, StringComparison.OrdinalIgnoreCase));
- return host?.IPAddress;
- }
- ...
- }
Advertisement
Add Comment
Please, Sign In to add comment