NetUtils.cs 1002 B

1234567891011121314151617181920212223242526272829303132333435
  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 TcpState GetState(this TcpClient tcpClient)
  12. {
  13. var foo = IPGlobalProperties
  14. .GetIPGlobalProperties()
  15. .GetActiveTcpConnections()
  16. .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  17. return foo?.State ?? TcpState.Unknown;
  18. }
  19. //TODO .NET6.0
  20. public static Task<(IPAddress, int, IPEndPoint)> ReceiveMessageFromAsync(this Socket client, EndPoint receive, byte[] array, SocketFlags flag)
  21. {
  22. return Task.Run(() =>
  23. {
  24. var length = client.ReceiveMessageFrom(array, 0, array.Length, ref flag, ref receive, out var ipPacketInformation);
  25. var local = ipPacketInformation.Address;
  26. Debug.WriteLine($@"{(IPEndPoint)receive} => {local} {length} 字节");
  27. return (local, length, (IPEndPoint)receive);
  28. });
  29. }
  30. }
  31. }