Socket.Accept Method

Definition

Creates a new Socket for a newly created connection.

C#
public System.Net.Sockets.Socket Accept();

Returns

A Socket for a newly created connection.

Exceptions

An error occurred when attempting to access the socket.

The Socket has been closed.

The accepting socket is not listening for connections. You must call Bind(EndPoint) and Listen(Int32) before calling Accept().

Examples

The following code example accepts a simple Socket connection.

C#
protected void AcceptMethod(Socket listeningSocket)
{
    Socket mySocket = listeningSocket.Accept();
}

Remarks

Accept synchronously extracts the first pending connection request from the connection request queue of the listening socket, and then creates and returns a new Socket. You cannot use this returned Socket to accept any additional connections from the connection queue. However, you can call the RemoteEndPoint method of the returned Socket to identify the remote host's network address and port number.

In blocking mode, Accept blocks until an incoming connection attempt is queued. Once a connection is accepted, the original Socket continues queuing incoming connection requests until you close it.

If you call this method using a non-blocking Socket, and no connection requests are queued, Accept throws a SocketException. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Note

Before calling the Accept method, you must first call the Listen method to listen for and queue incoming connection requests.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

See also