DefaultDnsQuery.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using STUN.Interfaces;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. namespace STUN.Client
  6. {
  7. public class DefaultDnsQuery : IDnsQuery
  8. {
  9. public async Task<IPAddress> QueryAsync(string host)
  10. {
  11. try
  12. {
  13. var ip = IsIPAddress(host);
  14. if (ip != null)
  15. {
  16. return ip;
  17. }
  18. var res = await Dns.GetHostAddressesAsync(host);
  19. return res.FirstOrDefault();
  20. }
  21. catch
  22. {
  23. return null;
  24. }
  25. }
  26. public IPAddress Query(string host)
  27. {
  28. try
  29. {
  30. var ip = IsIPAddress(host);
  31. if (ip != null)
  32. {
  33. return ip;
  34. }
  35. var res = Dns.GetHostAddresses(host);
  36. return res.FirstOrDefault();
  37. }
  38. catch
  39. {
  40. return null;
  41. }
  42. }
  43. private static IPAddress IsIPAddress(string host)
  44. {
  45. if (host != null && IPAddress.TryParse(host, out var ip))
  46. {
  47. return ip;
  48. }
  49. return null;
  50. }
  51. }
  52. }