diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs index 84cf302cb2b89..c60d8d8ee12c3 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs @@ -307,7 +307,7 @@ internal unsafe SocketError DoOperationConnectEx(Socket socket, SafeSocketHandle handle, PtrSocketAddressBuffer, _socketAddress!.Size, - (IntPtr)((byte*)_singleBufferHandle.Pointer + _offset), + (IntPtr)(bufferPtr + _offset), _count, out int bytesTransferred, overlapped); diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/Connect.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/Connect.cs index d045b94061f4d..8e1302e6c95a0 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/Connect.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/Connect.cs @@ -7,6 +7,7 @@ using Xunit; using Xunit.Abstractions; using Xunit.Sdk; +using System.Linq; namespace System.Net.Sockets.Tests { @@ -218,6 +219,58 @@ public ConnectTask(ITestOutputHelper output) : base(output) {} public sealed class ConnectEap : Connect { public ConnectEap(ITestOutputHelper output) : base(output) {} + + [Theory] + [PlatformSpecific(TestPlatforms.Windows)] + [InlineData(true)] + [InlineData(false)] + public async Task ConnectAsync_WithData_DataReceived(bool useArrayApi) + { + using Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + IPEndPoint serverEp = (IPEndPoint)listener.LocalEndPoint!; + listener.Listen(); + + var serverTask = Task.Run(async () => + { + using Socket handler = await listener.AcceptAsync(); + using var cts = new CancellationTokenSource(TestSettings.PassingTestTimeout); + byte[] recvBuffer = new byte[6]; + int received = await handler.ReceiveAsync(recvBuffer, SocketFlags.None, cts.Token); + Assert.True(received == 4); + + recvBuffer.AsSpan(0, 4).SequenceEqual(new byte[] { 2, 3, 4, 5 }); + }); + + using var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + + byte[] buffer = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; + + var mre = new ManualResetEventSlim(false); + var saea = new SocketAsyncEventArgs(); + saea.RemoteEndPoint = serverEp; + + // Slice the buffer to test the offset management: + if (useArrayApi) + { + saea.SetBuffer(buffer, 2, 4); + } + else + { + saea.SetBuffer(buffer.AsMemory(2, 4)); + } + + saea.Completed += (_, __) => mre.Set(); + + if (client.ConnectAsync(saea)) + { + Assert.True(mre.Wait(TestSettings.PassingTestTimeout), "Timed out while waiting for connection"); + } + + Assert.Equal(SocketError.Success, saea.SocketError); + + await serverTask; + } } public sealed class ConnectCancellableTask : Connect