NetUtils.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Diagnostics;
  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 static IPEndPoint? ParseEndpoint(string? str)
  13. {
  14. if (str is null)
  15. {
  16. return null;
  17. }
  18. var ipPort = str.Trim().Split(':');
  19. if (ipPort.Length < 2)
  20. {
  21. return null;
  22. }
  23. IPAddress? ip = null;
  24. if (ipPort.Length == 2 && IPAddress.TryParse(ipPort[0], out ip))
  25. {
  26. if (!IPAddress.TryParse(ipPort[0], out ip))
  27. {
  28. return null;
  29. }
  30. }
  31. else if (ipPort.Length > 2)
  32. {
  33. var ipStr = string.Join(@":", ipPort, 0, ipPort.Length - 1);
  34. if (!ipStr.StartsWith(@"[") || !ipStr.EndsWith(@"]") || !IPAddress.TryParse(ipStr, out ip))
  35. {
  36. return null;
  37. }
  38. }
  39. if (ip != null && ushort.TryParse(ipPort.Last(), out var port))
  40. {
  41. return new IPEndPoint(ip, port);
  42. }
  43. return null;
  44. }
  45. public static TcpState GetState(this TcpClient tcpClient)
  46. {
  47. var foo = IPGlobalProperties
  48. .GetIPGlobalProperties()
  49. .GetActiveTcpConnections()
  50. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  51. return foo?.State ?? TcpState.Unknown;
  52. }
  53. public static async Task<(IPAddress, int, IPEndPoint)> ReceiveMessageFromAsync(this Socket client, EndPoint receive, byte[] array, SocketFlags flag)
  54. {
  55. var tcs = new TaskCompletionSource<(IPAddress, int, IPEndPoint)>(TaskCreationOptions.RunContinuationsAsynchronously);
  56. _ = Task.Run(() =>
  57. {
  58. try
  59. {
  60. var length = client.ReceiveMessageFrom(array, 0, array.Length, ref flag, ref receive, out var ipPacketInformation);
  61. var local = ipPacketInformation.Address;
  62. Debug.WriteLine($@"{(IPEndPoint)receive} => {local} {length} 字节");
  63. tcs.SetResult((local, length, (IPEndPoint)receive));
  64. }
  65. catch (Exception ex)
  66. {
  67. tcs.SetException(ex);
  68. }
  69. });
  70. return await tcs.Task;
  71. }
  72. }
  73. }