Utils.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using NatTypeTester_Console.Net.STUN.Client;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. namespace NatTypeTester_Console
  7. {
  8. public static class Utils
  9. {
  10. public const string DefaultLocalEnd = @"0.0.0.0:0";
  11. public static IPEndPoint ParseEndpoint(string str)
  12. {
  13. var ipPort = str.Trim().Split(':');
  14. if (ipPort.Length == 2)
  15. {
  16. if (IPAddress.TryParse(ipPort[0], out var ip))
  17. {
  18. if (ushort.TryParse(ipPort[1], out var port))
  19. {
  20. return new IPEndPoint(ip, port);
  21. }
  22. }
  23. }
  24. return null;
  25. }
  26. public static (string, string, string) NatTypeTestCore(string local, string server, int port)
  27. {
  28. try
  29. {
  30. if (string.IsNullOrWhiteSpace(server))
  31. {
  32. Debug.WriteLine(@"[ERROR]: Please specify STUN server !");
  33. return (string.Empty, DefaultLocalEnd, string.Empty);
  34. }
  35. using (var socketV4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  36. {
  37. var ipe = ParseEndpoint(local) ?? new IPEndPoint(IPAddress.Any, 0);
  38. socketV4.Bind(ipe);
  39. var result = StunClient.Query(server, port, socketV4);
  40. return (
  41. result.NatType.ToString(),
  42. socketV4.LocalEndPoint.ToString(),
  43. result.NatType != NatType.UdpBlocked ? result.PublicEndPoint.ToString() : string.Empty
  44. );
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. Debug.WriteLine($@"[ERROR]: {ex}");
  50. return (string.Empty, DefaultLocalEnd, string.Empty);
  51. }
  52. }
  53. }
  54. }