NetUtils.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using STUN.Client;
  2. using STUN.StunResult;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.NetworkInformation;
  6. using System.Net.Sockets;
  7. using System.Threading.Tasks;
  8. namespace STUN.Utils
  9. {
  10. public static class NetUtils
  11. {
  12. public const string DefaultLocalEnd = @"0.0.0.0:0";
  13. public static IPEndPoint ParseEndpoint(string str)
  14. {
  15. var ipPort = str.Trim().Split(':');
  16. if (ipPort.Length < 2) return null;
  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 async Task<StunResult5389> NatBehaviorDiscovery(string server, ushort port, IPEndPoint local)
  40. {
  41. // proxy is not supported yet
  42. using var client = new StunClient5389UDP(server, port, local);
  43. return await client.QueryAsync();
  44. }
  45. public static TcpState GetState(this TcpClient tcpClient)
  46. {
  47. var foo = IPGlobalProperties.GetIPGlobalProperties()
  48. .GetActiveTcpConnections()
  49. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  50. return foo?.State ?? TcpState.Unknown;
  51. }
  52. }
  53. }