This documentation is archived and is not being maintained.

Socket.Accept Method

Creates a new Socket for a newly created connection.

[Visual Basic]
Public Function Accept() As Socket
public Socket Accept();
public: Socket* Accept();
public function Accept() : Socket;

Return Value

A Socket for a newly created connection.


Exception Type Condition
SocketException An error occurred when attempting to access the socket. See the Remarks section for more information.
ObjectDisposedException The Socket has been closed.
InvalidOperationException The Socket is not bound. You must call Bind before calling Accept.


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 will block until an incoming connection attempt is queued. After accepting a connection, the original Socket will continue 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 will throw a SocketException. If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Socket Version 2 API error code documentation in MSDN 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.


[Visual Basic, C#, C++] The following example accepts a simple Socket connection.

[Visual Basic] 
Dim mySocket As Socket = listeningSocket.Accept()
If mySocket Is Nothing Then
    Console.WriteLine("Winsock error: " & _
       Convert.ToString( _
End If

Socket mySocket = listeningSocket.Accept();

if (mySocket == null)
   Console.WriteLine("Winsock error: " + 
   Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()) );

Socket* mySocket = listeningSocket->Accept();

if (mySocket == 0)
   Console::WriteLine(S"Winsock error: {0}", Convert::ToString(System::Runtime::InteropServices::Marshal::GetLastWin32Error()) );

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.


Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Socket Class | Socket Members | System.Net.Sockets Namespace | Listen | RemoteEndPoint | Socket.BeginAccept