NetUtils.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 const string DefaultLocalEnd = @"0.0.0.0:0";
  10. public static IPEndPoint? ParseEndpoint(string str)
  11. {
  12. var ipPort = str.Trim().Split(':');
  13. if (ipPort.Length < 2)
  14. {
  15. return null;
  16. }
  17. IPAddress? ip = null;
  18. if (ipPort.Length == 2 && IPAddress.TryParse(ipPort[0], out ip))
  19. {
  20. if (!IPAddress.TryParse(ipPort[0], out ip))
  21. {
  22. return null;
  23. }
  24. }
  25. else if (ipPort.Length > 2)
  26. {
  27. var ipStr = string.Join(@":", ipPort, 0, ipPort.Length - 1);
  28. if (!ipStr.StartsWith(@"[") || !ipStr.EndsWith(@"]") || !IPAddress.TryParse(ipStr, out ip))
  29. {
  30. return null;
  31. }
  32. }
  33. if (ip != null && ushort.TryParse(ipPort.Last(), out var port))
  34. {
  35. return new IPEndPoint(ip, port);
  36. }
  37. return null;
  38. }
  39. public static TcpState GetState(this TcpClient tcpClient)
  40. {
  41. var foo = IPGlobalProperties
  42. .GetIPGlobalProperties()
  43. .GetActiveTcpConnections()
  44. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  45. return foo?.State ?? TcpState.Unknown;
  46. }
  47. }
  48. }