NetUtils.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Linq;
  2. using System.Net;
  3. using System.Net.NetworkInformation;
  4. using System.Net.Sockets;
  5. namespace STUN.Utils
  6. {
  7. public static class NetUtils
  8. {
  9. public static IPEndPoint? ParseEndpoint(string? str)
  10. {
  11. if (str is null)
  12. {
  13. return null;
  14. }
  15. var ipPort = str.Trim().Split(':');
  16. if (ipPort.Length < 2)
  17. {
  18. return null;
  19. }
  20. IPAddress? ip = null;
  21. if (ipPort.Length == 2 && IPAddress.TryParse(ipPort[0], out ip))
  22. {
  23. if (!IPAddress.TryParse(ipPort[0], out ip))
  24. {
  25. return null;
  26. }
  27. }
  28. else if (ipPort.Length > 2)
  29. {
  30. var ipStr = string.Join(@":", ipPort, 0, ipPort.Length - 1);
  31. if (!ipStr.StartsWith(@"[") || !ipStr.EndsWith(@"]") || !IPAddress.TryParse(ipStr, out ip))
  32. {
  33. return null;
  34. }
  35. }
  36. if (ip != null && ushort.TryParse(ipPort.Last(), out var port))
  37. {
  38. return new IPEndPoint(ip, port);
  39. }
  40. return null;
  41. }
  42. public static TcpState GetState(this TcpClient tcpClient)
  43. {
  44. var foo = IPGlobalProperties
  45. .GetIPGlobalProperties()
  46. .GetActiveTcpConnections()
  47. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  48. return foo?.State ?? TcpState.Unknown;
  49. }
  50. }
  51. }