NetUtils.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Diagnostics;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.NetworkInformation;
  5. using System.Net.Sockets;
  6. using System.Threading.Tasks;
  7. namespace STUN.Utils
  8. {
  9. public static class NetUtils
  10. {
  11. public static IPEndPoint? ParseEndpoint(string? str)
  12. {
  13. if (str is null)
  14. {
  15. return null;
  16. }
  17. var ipPort = str.Trim().Split(':');
  18. if (ipPort.Length < 2)
  19. {
  20. return null;
  21. }
  22. IPAddress? ip = null;
  23. if (ipPort.Length == 2 && IPAddress.TryParse(ipPort[0], out ip))
  24. {
  25. if (!IPAddress.TryParse(ipPort[0], out ip))
  26. {
  27. return null;
  28. }
  29. }
  30. else if (ipPort.Length > 2)
  31. {
  32. var ipStr = string.Join(@":", ipPort, 0, ipPort.Length - 1);
  33. if (!ipStr.StartsWith(@"[") || !ipStr.EndsWith(@"]") || !IPAddress.TryParse(ipStr, out ip))
  34. {
  35. return null;
  36. }
  37. }
  38. if (ip != null && ushort.TryParse(ipPort.Last(), out var port))
  39. {
  40. return new IPEndPoint(ip, port);
  41. }
  42. return null;
  43. }
  44. public static TcpState GetState(this TcpClient tcpClient)
  45. {
  46. var foo = IPGlobalProperties
  47. .GetIPGlobalProperties()
  48. .GetActiveTcpConnections()
  49. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  50. return foo?.State ?? TcpState.Unknown;
  51. }
  52. public static Task<(IPAddress, int, IPEndPoint)> ReceiveMessageFromAsync(this Socket client, EndPoint receive, byte[] array, SocketFlags flag)
  53. {
  54. return Task.Run(() =>
  55. {
  56. var length = client.ReceiveMessageFrom(array, 0, array.Length, ref flag, ref receive, out var ipPacketInformation);
  57. var local = ipPacketInformation.Address;
  58. Debug.WriteLine($@"{(IPEndPoint)receive} => {local} {length} 字节");
  59. return (local, length, (IPEndPoint)receive);
  60. });
  61. }
  62. }
  63. }