Skip to content

Socket ConnectAsync returns successfully with a non-connected socket if canceled #75889

@bentoi

Description

@bentoi

Description

Socket.ConnetAsync sporadically returns successfully but the socket is not connected (Socket.Connected == false). This occurs when canceling ConnectAsync while it's in progress after the server side accepts the socket.

Reproduction Steps

using System.Net;
using System.Net.Sockets;

while (true)
{
    using var serverSocket =  new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
    serverSocket.Listen();

    using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    using var cts = new CancellationTokenSource();

    ValueTask connectTask = socket.ConnectAsync(serverSocket.LocalEndPoint!, cts.Token);
    using var _ = await serverSocket.AcceptAsync();
    cts.Cancel();

    try
    {
        await connectTask;
        if (!socket.Connected)
        {
            Console.Error.WriteLine("unexpected non-connected socket after successfull ConnectAsync");
            return 1;
        }
    }
    catch (OperationCanceledException)
    {
        // Expected if canceled before connect.
    }
}

Expected behavior

The ConnectAsync call should either throw OperationCanceledException or return a connected socket.

Actual behavior

ConnectAsync returns but the socket is not connected

Regression?

No response

Known Workarounds

No response

Configuration

.NET Core 6
Linux Debian Buster and macOS

Other information

No response

Metadata

Metadata

Assignees

Labels

area-System.Net.Socketsin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions