StunServer.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace STUN;
  5. public class StunServer
  6. {
  7. public string Hostname { get; }
  8. public ushort Port { get; }
  9. public const ushort DefaultPort = 3478;
  10. public const ushort DefaultTlsPort = 5349;
  11. public StunServer()
  12. {
  13. Hostname = @"stun.syncthing.net";
  14. Port = DefaultPort;
  15. }
  16. private StunServer(string hostname, ushort port)
  17. {
  18. Hostname = hostname;
  19. Port = port;
  20. }
  21. public static bool TryParse(string s, [NotNullWhen(true)] out StunServer? result, ushort defaultPort = DefaultPort)
  22. {
  23. if (!HostnameEndpoint.TryParse(s, out HostnameEndpoint? host, defaultPort))
  24. {
  25. result = null;
  26. return false;
  27. }
  28. result = new StunServer(host.Hostname, host.Port);
  29. return true;
  30. }
  31. public override string ToString()
  32. {
  33. if (Port is DefaultPort)
  34. {
  35. return Hostname;
  36. }
  37. if (IPAddress.TryParse(Hostname, out IPAddress? ip) && ip.AddressFamily is AddressFamily.InterNetworkV6)
  38. {
  39. return $@"[{ip}]:{Port}";
  40. }
  41. return $@"{Hostname}:{Port}";
  42. }
  43. }