public async ValueTask WriteAsync(ReadOnlyMemory <byte> buffer) { var packData = UdpPackData.Parse(buffer); if (!_addressMap.TryGetValue(packData.Remote, out var endPoint)) { if (IPAddress.TryParse(packData.Remote.Address, out var address)) { endPoint = new IPEndPoint(address, packData.Remote.Port); } else { foreach (var addr in await Dns.GetHostAddressesAsync(packData.Remote.Address)) { if (addr.AddressFamily == AddressFamily.InterNetwork) { address = addr; break; } } endPoint = new IPEndPoint(address, packData.Remote.Port); } _addressMap.TryAdd(packData.Remote, endPoint); _endPointMap.TryAdd(endPoint, packData.Remote); } await _udp.SendAsync(packData.Data, packData.Data.Length, endPoint); lastRemote = packData.Remote; }
public async ValueTask <int> ReadAsync(Memory <byte> buffer) { var readTask = _udp.ReceiveAsync(); var complete = await Task.WhenAny(readTask, Task.Delay(TimeSpan.FromSeconds(30))); if (complete != readTask) { Logger.LogWarning("Udp receive timeout, {0}", Id); return(0); } var result = readTask.Result; if (!_endPointMap.TryGetValue(result.RemoteEndPoint, out var remote)) { remote = lastRemote; } var resultBytes = new UdpPackData() { Data = result.Buffer, Remote = remote }.ToBytes(); if (buffer.Length < resultBytes.Length) { return(0); } resultBytes.CopyTo(buffer); return(resultBytes.Length); }
public static Socks5UdpRelayRequest Parse(byte[] buffer) { var result = new Socks5UdpRelayRequest { Frag = buffer[2], Data = UdpPackData.Parse(new ReadOnlyMemory <byte>(buffer, 3, buffer.Length - 3)) }; return(result); }