Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Does Socket.AcceptAsync throw SocketException for any transient reason?
Parent
Does Socket.AcceptAsync throw SocketException for any transient reason?
I'm writing exception handling around a call to Socket.AcceptAsync
in a loop. One of the exceptions it's documented to throw is SocketException
, but the documentation is vague:
An error occurred when attempting to access the socket.
I want to know if AcceptAsync
throws SocketException
for any transient reason. In particular, is there anything the remote client could do to cause it to throw? If I don't account for this, my program could be subject to denial of service attacks.
Post
The source code for the Socket.AcceptAsync class seems to be this one.
The relevant code (the one related to exceptions being raised) is the following:
private bool AcceptAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(e);
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e));
}
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustbind);
}
if (!_isListening)
{
throw new InvalidOperationException(SR.net_sockets_mustlisten);
}
SocketError socketError;
try
{
socketError = e.DoOperationAccept(this, _handle, acceptHandle, cancellationToken);
}
catch (Exception ex)
{
SocketsTelemetry.Log.AfterAccept(SocketError.Interrupted, ex.Message);
// Clear in-use flag on event args object.
e.Complete();
throw;
}
return socketError == SocketError.IOPending;
}
Based on this, I would consider handling the following exception types:
- ObjectDisposedException
- ArgumentNullException
- InvalidOperationException
- Exception (that is, even the library creators expect "other" exception types)
0 comment threads