Коды ошибок socket error

description ms.assetid title ms.topic ms.date

Windows Sockets (Winsock) error codes returned by the WSAGetLastError function.

50b924f3-2c88-443b-8a90-4293fe5c3048

Windows Sockets Error Codes (Winsock2.h)

reference

05/31/2018

Windows Sockets Error Codes

Most Windows Sockets 2 functions do not return the specific cause of an error when the function returns. For information, see the Handling Winsock Errors topic.

The WSAGetLastError function returns the last error that occurred for the calling thread. When a particular Windows Sockets function indicates an error has occurred, this function should be called immediately to retrieve the extended error code for the failing function call. These error codes and a short text description associated with an error code are defined in the Winerror.h header file. The FormatMessage function can be used to obtain the message string for the returned error.

For information on how to handle error codes when porting socket applications to Winsock, see Error Codes — errno, h_errno and WSAGetLastError.

The following list describes the possible error codes returned by the WSAGetLastError function. Errors are listed in numerical order with the error macro name. Some error codes defined in the Winsock2.h header file are not returned from any function.

Return code/value Description

WSA_INVALID_HANDLE
6
Specified event object handle is invalid.
An application attempts to use an event object, but the specified handle is not valid.

WSA_NOT_ENOUGH_MEMORY
8
Insufficient memory available.
An application used a Windows Sockets function that directly maps to a Windows function. The Windows function is indicating a lack of required memory resources.

WSA_INVALID_PARAMETER
87
One or more parameters are invalid.
An application used a Windows Sockets function which directly maps to a Windows function. The Windows function is indicating a problem with one or more parameters.

WSA_OPERATION_ABORTED
995
Overlapped operation aborted.
An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.

WSA_IO_INCOMPLETE
996
Overlapped I/O event object not in signaled state.
The application has tried to determine the status of an overlapped operation which is not yet completed. Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete.

WSA_IO_PENDING
997
Overlapped operations will complete later.

The application has initiated an overlapped operation that cannot be completed immediately. A completion indication will be given later when the operation has been completed.

WSAEINTR
10004
Interrupted function call.
A blocking operation was interrupted by a call to WSACancelBlockingCall.

WSAEBADF
10009
File handle is not valid.
The file handle supplied is not valid.

WSAEACCES
10013
Permission denied.
An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.

WSAEFAULT
10014
Bad address.
The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).

WSAEINVAL
10022
Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.

WSAEMFILE
10024
Too many open files.
Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.

WSAEWOULDBLOCK
10035
Resource temporarily unavailable.
This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.

WSAEINPROGRESS
10036
Operation now in progress.
A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.

WSAEALREADY
10037
Operation already in progress.
An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.

WSAENOTSOCK
10038
Socket operation on nonsocket.
An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.

WSAEDESTADDRREQ
10039
Destination address required.
A required address was omitted from an operation on a socket. For example, this error is returned if sendto is called with the remote address of ADDR_ANY.

WSAEMSGSIZE
10040
Message too long.
A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.

WSAEPROTOTYPE
10041
Protocol wrong type for socket.
A protocol was specified in the socket function call that does not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM.

WSAENOPROTOOPT
10042
Bad protocol option.
An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.

WSAEPROTONOSUPPORT
10043
Protocol not supported.
The requested protocol has not been configured into the system, or no implementation for it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.

WSAESOCKTNOSUPPORT
10044
Socket type not supported.
The support for the specified socket type does not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all.

WSAEOPNOTSUPP
10045
Operation not supported.
The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.

WSAEPFNOSUPPORT
10046
Protocol family not supported.
The protocol family has not been configured into the system or no implementation for it exists. This message has a slightly different meaning from WSAEAFNOSUPPORT. However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.

WSAEAFNOSUPPORT
10047
Address family not supported by protocol family.
An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.

WSAEADDRINUSE
10048
Address already in use.
Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all—connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.

WSAEADDRNOTAVAIL
10049
Cannot assign requested address.
The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).

WSAENETDOWN
10050
Network is down.
A socket operation encountered a dead network. This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.

WSAENETUNREACH
10051
Network is unreachable.
A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host.

WSAENETRESET
10052
Network dropped connection on reset.
The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed.

WSAECONNABORTED
10053
Software caused connection abort.
An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.

WSAECONNRESET
10054
Connection reset by peer.
An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

WSAENOBUFS
10055
No buffer space available.
An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.

WSAEISCONN
10056
Socket is already connected.
A connect request was made on an already-connected socket. Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (for SOCK_STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.

WSAENOTCONN
10057
Socket is not connected.
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also return this error—for example, setsockopt setting SO_KEEPALIVE if the connection has been reset.

WSAESHUTDOWN
10058
Cannot send after socket shutdown.
A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.

WSAETOOMANYREFS
10059
Too many references.
Too many references to some kernel object.

WSAETIMEDOUT
10060
Connection timed out.
A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.

WSAECONNREFUSED
10061
Connection refused.
No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

WSAELOOP
10062
Cannot translate name.
Cannot translate a name.

WSAENAMETOOLONG
10063
Name too long.
A name component or a name was too long.

WSAEHOSTDOWN
10064
Host is down.
A socket operation failed because the destination host is down. A socket operation encountered a dead host. Networking activity on the local host has not been initiated. These conditions are more likely to be indicated by the error WSAETIMEDOUT.

WSAEHOSTUNREACH
10065
No route to host.
A socket operation was attempted to an unreachable host. See WSAENETUNREACH.

WSAENOTEMPTY
10066
Directory not empty.
Cannot remove a directory that is not empty.

WSAEPROCLIM
10067
Too many processes.
A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously. WSAStartup may fail with this error if the limit has been reached.

WSAEUSERS
10068
User quota exceeded.
Ran out of user quota.

WSAEDQUOT
10069
Disk quota exceeded.
Ran out of disk quota.

WSAESTALE
10070
Stale file handle reference.
The file handle reference is no longer available.

WSAEREMOTE
10071
Item is remote.
The item is not available locally.

WSASYSNOTREADY
10091
Network subsystem is unavailable.
This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable. Users should check:
  • That the appropriate Windows Sockets DLL file is in the current path.
  • That they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded.
  • The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.

WSAVERNOTSUPPORTED
10092
Winsock.dll version out of range.
The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.

WSANOTINITIALISED
10093
Successful WSAStartup not yet performed.
Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

WSAEDISCON
10101
Graceful shutdown in progress.
Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.

WSAENOMORE
10102
No more results.
No more results can be returned by the WSALookupServiceNext function.

WSAECANCELLED
10103
Call has been canceled.
A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.

WSAEINVALIDPROCTABLE
10104
Procedure call table is invalid.
The service provider procedure call table is invalid. A service provider returned a bogus procedure table to Ws2_32.dll. This is usually caused by one or more of the function pointers being NULL.

WSAEINVALIDPROVIDER
10105
Service provider is invalid.
The requested service provider is invalid. This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found. This error is also returned if the service provider returned a version number other than 2.0.

WSAEPROVIDERFAILEDINIT
10106
Service provider failed to initialize.
The requested service provider could not be loaded or initialized. This error is returned if either a service provider’s DLL could not be loaded (LoadLibrary failed) or the provider’s WSPStartup or NSPStartup function failed.

WSASYSCALLFAILURE
10107
System call failure.
A system call that should never fail has failed. This is a generic error code, returned under various conditions.
Returned when a system call that should never fail does fail. For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
Returned when a provider does not return SUCCESS and does not provide an extended error code. Can indicate a service provider implementation error.

WSASERVICE_NOT_FOUND
10108
Service not found.
No such service is known. The service cannot be found in the specified name space.

WSATYPE_NOT_FOUND
10109
Class type not found.
The specified class was not found.

WSA_E_NO_MORE
10110
No more results.
No more results can be returned by the WSALookupServiceNext function.

WSA_E_CANCELLED
10111
Call was canceled.
A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.

WSAEREFUSED
10112
Database query was refused.
A database query failed because it was actively refused.

WSAHOST_NOT_FOUND
11001
Host not found.
No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.

WSATRY_AGAIN
11002
Nonauthoritative host not found.
This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.

WSANO_RECOVERY
11003
This is a nonrecoverable error.
This indicates that some sort of nonrecoverable error occurred during a database lookup. This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.

WSANO_DATA
11004
Valid name, no data record of requested type.
The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.

WSA_QOS_RECEIVERS
11005
QoS receivers.
At least one QoS reserve has arrived.

WSA_QOS_SENDERS
11006
QoS senders.
At least one QoS send path has arrived.

WSA_QOS_NO_SENDERS
11007
No QoS senders.
There are no QoS senders.

WSA_QOS_NO_RECEIVERS
11008
QoS no receivers.
There are no QoS receivers.

WSA_QOS_REQUEST_CONFIRMED
11009
QoS request confirmed.
The QoS reserve request has been confirmed.

WSA_QOS_ADMISSION_FAILURE
11010
QoS admission error.
A QoS error occurred due to lack of resources.

WSA_QOS_POLICY_FAILURE
11011
QoS policy failure.
The QoS request was rejected because the policy system couldn’t allocate the requested resource within the existing policy.

WSA_QOS_BAD_STYLE
11012
QoS bad style.
An unknown or conflicting QoS style was encountered.

WSA_QOS_BAD_OBJECT
11013
QoS bad object.
A problem was encountered with some part of the filterspec or the provider-specific buffer in general.

WSA_QOS_TRAFFIC_CTRL_ERROR
11014
QoS traffic control error.
An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API. This could be due to an out of memory error or to an internal QoS provider error.

WSA_QOS_GENERIC_ERROR
11015
QoS generic error.
A general QoS error.

WSA_QOS_ESERVICETYPE
11016
QoS service type error.
An invalid or unrecognized service type was found in the QoS flowspec.

WSA_QOS_EFLOWSPEC
11017
QoS flowspec error.
An invalid or inconsistent flowspec was found in the QOS structure.

WSA_QOS_EPROVSPECBUF
11018
Invalid QoS provider buffer.
An invalid QoS provider-specific buffer.

WSA_QOS_EFILTERSTYLE
11019
Invalid QoS filter style.
An invalid QoS filter style was used.

WSA_QOS_EFILTERTYPE
11020
Invalid QoS filter type.
An invalid QoS filter type was used.

WSA_QOS_EFILTERCOUNT
11021
Incorrect QoS filter count.
An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.

WSA_QOS_EOBJLENGTH
11022
Invalid QoS object length.
An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.

WSA_QOS_EFLOWCOUNT
11023
Incorrect QoS flow count.
An incorrect number of flow descriptors was specified in the QoS structure.

WSA_QOS_EUNKOWNPSOBJ
11024
Unrecognized QoS object.
An unrecognized object was found in the QoS provider-specific buffer.

WSA_QOS_EPOLICYOBJ
11025
Invalid QoS policy object.
An invalid policy object was found in the QoS provider-specific buffer.

WSA_QOS_EFLOWDESC
11026
Invalid QoS flow descriptor.
An invalid QoS flow descriptor was found in the flow descriptor list.

WSA_QOS_EPSFLOWSPEC
11027
Invalid QoS provider-specific flowspec.
An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.

WSA_QOS_EPSFILTERSPEC
11028
Invalid QoS provider-specific filterspec.
An invalid FILTERSPEC was found in the QoS provider-specific buffer.

WSA_QOS_ESDMODEOBJ
11029
Invalid QoS shape discard mode object.
An invalid shape discard mode object was found in the QoS provider-specific buffer.

WSA_QOS_ESHAPERATEOBJ
11030
Invalid QoS shaping rate object.
An invalid shaping rate object was found in the QoS provider-specific buffer.

WSA_QOS_RESERVED_PETYPE
11031
Reserved policy QoS element type.
A reserved policy element was found in the QoS provider-specific buffer.

Requirements

Requirement Value
Header
Winsock2.h;
Winerror.h

See also

Error Codes — errno, h_errno and WSAGetLastError

Handling Winsock Errors

FormatMessage

WSAGetLastError

This blog post was originally posted on JetBrains .NET blog.

Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:

protected virtual bool ShouldRetryConnection (Exception ex, int attemptNumber)
{
    var sx = ex as SocketException;
    if (sx != null) {
        if (sx.ErrorCode == 10061) //connection refused
            return true;
    }
    return false;
}

In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException documentation, we will learn that this class has three different properties with error codes:

  • SocketError SocketErrorCode: Gets the error code that is associated with this exception.
  • int ErrorCode: Gets the error code that is associated with this exception.
  • int NativeErrorCode: Gets the Win32 error code associated with this exception.

What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection on .NET Core? Let’s figure it all out!

Digging into the problem

Let’s start with the following program, which prints error code property values for SocketError.ConnectionRefused:

var se = new SocketException((int) SocketError.ConnectionRefused);
Console.WriteLine((int)se.SocketErrorCode);
Console.WriteLine(se.ErrorCode);
Console.WriteLine(se.NativeErrorCode);

If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:

SocketErrorCode ErrorCode NativeErrorCode
.NET Framework 10061 10061 10061
Mono 10061 10061 10061
.NET Core 10061 10061 10061

10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED).
Now let’s run the same program on Linux:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 111 111

As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode and NativeErrorCode (111).
Finally, let’s check macOS:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 61 61

Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode and NativeErrorCode.
In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED):

  • AIX: 79
  • HP-UX: 239
  • Solaris: 146

For a better understanding of what’s going on, let’s check out the source code of all the properties.

SocketErrorCode

SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements are the same on all the runtimes (see its implementation in .NET Framework, .NET Core 3.1.3, and Mono 6.8.0.105):

public enum SocketError
{
    SocketError = -1, // 0xFFFFFFFF
    Success = 0,
    OperationAborted = 995, // 0x000003E3
    IOPending = 997, // 0x000003E5
    Interrupted = 10004, // 0x00002714
    AccessDenied = 10013, // 0x0000271D
    Fault = 10014, // 0x0000271E
    InvalidArgument = 10022, // 0x00002726
    TooManyOpenSockets = 10024, // 0x00002728
    WouldBlock = 10035, // 0x00002733
    InProgress = 10036, // 0x00002734
    AlreadyInProgress = 10037, // 0x00002735
    NotSocket = 10038, // 0x00002736
    DestinationAddressRequired = 10039, // 0x00002737
    MessageSize = 10040, // 0x00002738
    ProtocolType = 10041, // 0x00002739
    ProtocolOption = 10042, // 0x0000273A
    ProtocolNotSupported = 10043, // 0x0000273B
    SocketNotSupported = 10044, // 0x0000273C
    OperationNotSupported = 10045, // 0x0000273D
    ProtocolFamilyNotSupported = 10046, // 0x0000273E
    AddressFamilyNotSupported = 10047, // 0x0000273F
    AddressAlreadyInUse = 10048, // 0x00002740
    AddressNotAvailable = 10049, // 0x00002741
    NetworkDown = 10050, // 0x00002742
    NetworkUnreachable = 10051, // 0x00002743
    NetworkReset = 10052, // 0x00002744
    ConnectionAborted = 10053, // 0x00002745
    ConnectionReset = 10054, // 0x00002746
    NoBufferSpaceAvailable = 10055, // 0x00002747
    IsConnected = 10056, // 0x00002748
    NotConnected = 10057, // 0x00002749
    Shutdown = 10058, // 0x0000274A
    TimedOut = 10060, // 0x0000274C
    ConnectionRefused = 10061, // 0x0000274D
    HostDown = 10064, // 0x00002750
    HostUnreachable = 10065, // 0x00002751
    ProcessLimit = 10067, // 0x00002753
    SystemNotReady = 10091, // 0x0000276B
    VersionNotSupported = 10092, // 0x0000276C
    NotInitialized = 10093, // 0x0000276D
    Disconnecting = 10101, // 0x00002775
    TypeNotFound = 10109, // 0x0000277D
    HostNotFound = 11001, // 0x00002AF9
    TryAgain = 11002, // 0x00002AFA
    NoRecovery = 11003, // 0x00002AFB
    NoData = 11004, // 0x00002AFC
}

These values correspond to the Windows Sockets Error Codes.

NativeErrorCode

In .NET Framework and Mono, SocketErrorCode and NativeErrorCode always have the same values:

public SocketError SocketErrorCode {
    //
    // the base class returns the HResult with this property
    // we need the Win32 Error Code, hence the override.
    //
    get {
        return (SocketError)NativeErrorCode;
    }
}

In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):

public SocketException(int errorCode) : this((SocketError)errorCode)
// ...
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))

The Windows implementation of GetNativeErrorForSocketError is trivial (see SocketException.Windows.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    // SocketError values map directly to Win32 error codes
    return (int)error;
}

The Unix implementation is more complicated (see SocketException.Unix.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    int nativeErr = (int)error;
    if (error != SocketError.SocketError)
    {
        Interop.Error interopErr;

        // If an interop error was not found, then don't invoke Info().RawErrno as that will fail with assert.
        if (SocketErrorPal.TryGetNativeErrorForSocketError(error, out interopErr))
        {
            nativeErr = interopErr.Info().RawErrno;
        }
    }

    return nativeErr;
}

TryGetNativeErrorForSocketError should convert SocketError to the native Unix error code.
Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):

private const int NativeErrorToSocketErrorCount = 42; private const int SocketErrorToNativeErrorCount = 40;  // No Interop.Errors are included for the following SocketErrors, as there's no good mapping: // - SocketError.NoRecovery // - SocketError.NotInitialized // - SocketError.ProcessLimit // - SocketError.SocketError // - SocketError.SystemNotReady // - SocketError.TypeNotFound // - SocketError.VersionNotSupported  private static readonly Dictionary<Interop.Error, SocketError> s_nativeErrorToSocketError = new Dictionary<Interop.Error, SocketError>(NativeErrorToSocketErrorCount) {  { Interop.Error.EACCES, SocketError.AccessDenied },  { Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse },  { Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable },  { Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported },  { Interop.Error.EAGAIN, SocketError.WouldBlock },  { Interop.Error.EALREADY, SocketError.AlreadyInProgress },  { Interop.Error.EBADF, SocketError.OperationAborted },  { Interop.Error.ECANCELED, SocketError.OperationAborted },  { Interop.Error.ECONNABORTED, SocketError.ConnectionAborted },  { Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused },  { Interop.Error.ECONNRESET, SocketError.ConnectionReset },  { Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired },  { Interop.Error.EFAULT, SocketError.Fault },  { Interop.Error.EHOSTDOWN, SocketError.HostDown },  { Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available  { Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable },  { Interop.Error.EINPROGRESS, SocketError.InProgress },  { Interop.Error.EINTR, SocketError.Interrupted },  { Interop.Error.EINVAL, SocketError.InvalidArgument },  { Interop.Error.EISCONN, SocketError.IsConnected },  { Interop.Error.EMFILE, SocketError.TooManyOpenSockets },  { Interop.Error.EMSGSIZE, SocketError.MessageSize },  { Interop.Error.ENETDOWN, SocketError.NetworkDown },  { Interop.Error.ENETRESET, SocketError.NetworkReset },  { Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable },  { Interop.Error.ENFILE, SocketError.TooManyOpenSockets },  { Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable },  { Interop.Error.ENODATA, SocketError.NoData },  { Interop.Error.ENOENT, SocketError.AddressNotAvailable },  { Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption },  { Interop.Error.ENOTCONN, SocketError.NotConnected },  { Interop.Error.ENOTSOCK, SocketError.NotSocket },  { Interop.Error.ENOTSUP, SocketError.OperationNotSupported },  { Interop.Error.EPERM, SocketError.AccessDenied },  { Interop.Error.EPIPE, SocketError.Shutdown },  { Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported },  { Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported },  { Interop.Error.EPROTOTYPE, SocketError.ProtocolType },  { Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported },  { Interop.Error.ESHUTDOWN, SocketError.Disconnecting },  { Interop.Error.SUCCESS, SocketError.Success },  { Interop.Error.ETIMEDOUT, SocketError.TimedOut }, };  private static readonly Dictionary<SocketError, Interop.Error> s_socketErrorToNativeError = new Dictionary<SocketError, Interop.Error>(SocketErrorToNativeErrorCount) {  // This is *mostly* an inverse mapping of s_nativeErrorToSocketError. However, some options have multiple mappings and thus  // can't be inverted directly. Other options don't have a mapping from native to SocketError, but when presented with a SocketError,  // we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but  // SocketError.IOPending also maps closest to EINPROGRESS. As such, roundtripping won't necessarily provide the original value 100% of the time,  // but it's the best we can do given the mismatch between Interop.Error and SocketError.   { SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM  { SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE },  { SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL },  { SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT },  { SocketError.AlreadyInProgress, Interop.Error.EALREADY },  { SocketError.ConnectionAborted, Interop.Error.ECONNABORTED },  { SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED },  { SocketError.ConnectionReset, Interop.Error.ECONNRESET },  { SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ },  { SocketError.Disconnecting, Interop.Error.ESHUTDOWN },  { SocketError.Fault, Interop.Error.EFAULT },  { SocketError.HostDown, Interop.Error.EHOSTDOWN },  { SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND },  { SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH },  { SocketError.InProgress, Interop.Error.EINPROGRESS },  { SocketError.Interrupted, Interop.Error.EINTR },  { SocketError.InvalidArgument, Interop.Error.EINVAL },  { SocketError.IOPending, Interop.Error.EINPROGRESS },  { SocketError.IsConnected, Interop.Error.EISCONN },  { SocketError.MessageSize, Interop.Error.EMSGSIZE },  { SocketError.NetworkDown, Interop.Error.ENETDOWN },  { SocketError.NetworkReset, Interop.Error.ENETRESET },  { SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH },  { SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS },  { SocketError.NoData, Interop.Error.ENODATA },  { SocketError.NotConnected, Interop.Error.ENOTCONN },  { SocketError.NotSocket, Interop.Error.ENOTSOCK },  { SocketError.OperationAborted, Interop.Error.ECANCELED },  { SocketError.OperationNotSupported, Interop.Error.ENOTSUP },  { SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT },  { SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT },  { SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT },  { SocketError.ProtocolType, Interop.Error.EPROTOTYPE },  { SocketError.Shutdown, Interop.Error.EPIPE },  { SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT },  { SocketError.Success, Interop.Error.SUCCESS },  { SocketError.TimedOut, Interop.Error.ETIMEDOUT },  { SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE  { SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing  { SocketError.WouldBlock, Interop.Error.EAGAIN }, };  internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno) {  return s_socketErrorToNativeError.TryGetValue(error, out errno); } 

Once we have an instance of Interop.Error, we call interopErr.Info().RawErrno. The implementation of RawErrno can be found in Interop.Errors.cs:

internal int RawErrno {  get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; } }  [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")] internal static extern int ConvertErrorPalToPlatform(Error error); 

Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:

$ errno -ls EPERM 1 Operation not permitted ENOENT 2 No such file or directory ESRCH 3 No such process EINTR 4 Interrupted system call EIO 5 Input/output error ENXIO 6 No such device or address E2BIG 7 Argument list too long ENOEXEC 8 Exec format error EBADF 9 Bad file descriptor ECHILD 10 No child processes EAGAIN 11 Resource temporarily unavailable ENOMEM 12 Cannot allocate memory EACCES 13 Permission denied EFAULT 14 Bad address ENOTBLK 15 Block device required EBUSY 16 Device or resource busy EEXIST 17 File exists EXDEV 18 Invalid cross-device link ENODEV 19 No such device ENOTDIR 20 Not a directory EISDIR 21 Is a directory EINVAL 22 Invalid argument ENFILE 23 Too many open files in system EMFILE 24 Too many open files ENOTTY 25 Inappropriate ioctl for device ETXTBSY 26 Text file busy EFBIG 27 File too large ENOSPC 28 No space left on device ESPIPE 29 Illegal seek EROFS 30 Read-only file system EMLINK 31 Too many links EPIPE 32 Broken pipe EDOM 33 Numerical argument out of domain ERANGE 34 Numerical result out of range EDEADLK 35 Resource deadlock avoided ENAMETOOLONG 36 File name too long ENOLCK 37 No locks available ENOSYS 38 Function not implemented ENOTEMPTY 39 Directory not empty ELOOP 40 Too many levels of symbolic links EWOULDBLOCK 11 Resource temporarily unavailable ENOMSG 42 No message of desired type EIDRM 43 Identifier removed ECHRNG 44 Channel number out of range EL2NSYNC 45 Level 2 not synchronized EL3HLT 46 Level 3 halted EL3RST 47 Level 3 reset ELNRNG 48 Link number out of range EUNATCH 49 Protocol driver not attached ENOCSI 50 No CSI structure available EL2HLT 51 Level 2 halted EBADE 52 Invalid exchange EBADR 53 Invalid request descriptor EXFULL 54 Exchange full ENOANO 55 No anode EBADRQC 56 Invalid request code EBADSLT 57 Invalid slot EDEADLOCK 35 Resource deadlock avoided EBFONT 59 Bad font file format ENOSTR 60 Device not a stream ENODATA 61 No data available ETIME 62 Timer expired ENOSR 63 Out of streams resources ENONET 64 Machine is not on the network ENOPKG 65 Package not installed EREMOTE 66 Object is remote ENOLINK 67 Link has been severed EADV 68 Advertise error ESRMNT 69 Srmount error ECOMM 70 Communication error on send EPROTO 71 Protocol error EMULTIHOP 72 Multihop attempted EDOTDOT 73 RFS specific error EBADMSG 74 Bad message EOVERFLOW 75 Value too large for defined data type ENOTUNIQ 76 Name not unique on network EBADFD 77 File descriptor in bad state EREMCHG 78 Remote address changed ELIBACC 79 Can not access a needed shared library ELIBBAD 80 Accessing a corrupted shared library ELIBSCN 81 .lib section in a.out corrupted ELIBMAX 82 Attempting to link in too many shared libraries ELIBEXEC 83 Cannot exec a shared library directly EILSEQ 84 Invalid or incomplete multibyte or wide character ERESTART 85 Interrupted system call should be restarted ESTRPIPE 86 Streams pipe error EUSERS 87 Too many users ENOTSOCK 88 Socket operation on non-socket EDESTADDRREQ 89 Destination address required EMSGSIZE 90 Message too long EPROTOTYPE 91 Protocol wrong type for socket ENOPROTOOPT 92 Protocol not available EPROTONOSUPPORT 93 Protocol not supported ESOCKTNOSUPPORT 94 Socket type not supported EOPNOTSUPP 95 Operation not supported EPFNOSUPPORT 96 Protocol family not supported EAFNOSUPPORT 97 Address family not supported by protocol EADDRINUSE 98 Address already in use EADDRNOTAVAIL 99 Cannot assign requested address ENETDOWN 100 Network is down ENETUNREACH 101 Network is unreachable ENETRESET 102 Network dropped connection on reset ECONNABORTED 103 Software caused connection abort ECONNRESET 104 Connection reset by peer ENOBUFS 105 No buffer space available EISCONN 106 Transport endpoint is already connected ENOTCONN 107 Transport endpoint is not connected ESHUTDOWN 108 Cannot send after transport endpoint shutdown ETOOMANYREFS 109 Too many references: cannot splice ETIMEDOUT 110 Connection timed out ECONNREFUSED 111 Connection refused EHOSTDOWN 112 Host is down EHOSTUNREACH 113 No route to host EALREADY 114 Operation already in progress EINPROGRESS 115 Operation now in progress ESTALE 116 Stale file handle EUCLEAN 117 Structure needs cleaning ENOTNAM 118 Not a XENIX named type file ENAVAIL 119 No XENIX semaphores available EISNAM 120 Is a named type file EREMOTEIO 121 Remote I/O error EDQUOT 122 Disk quota exceeded ENOMEDIUM 123 No medium found EMEDIUMTYPE 124 Wrong medium type ECANCELED 125 Operation canceled ENOKEY 126 Required key not available EKEYEXPIRED 127 Key has expired EKEYREVOKED 128 Key has been revoked EKEYREJECTED 129 Key was rejected by service EOWNERDEAD 130 Owner died ENOTRECOVERABLE 131 State not recoverable ERFKILL 132 Operation not possible due to RF-kill EHWPOISON 133 Memory page has hardware error ENOTSUP 95 Operation not supported 

Note that errno may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils to get this utility.
Here is a typical output on macOS:

$ errno -ls EPERM 1 Operation not permitted ENOENT 2 No such file or directory ESRCH 3 No such process EINTR 4 Interrupted system call EIO 5 Input/output error ENXIO 6 Device not configured E2BIG 7 Argument list too long ENOEXEC 8 Exec format error EBADF 9 Bad file descriptor ECHILD 10 No child processes EDEADLK 11 Resource deadlock avoided ENOMEM 12 Cannot allocate memory EACCES 13 Permission denied EFAULT 14 Bad address ENOTBLK 15 Block device required EBUSY 16 Resource busy EEXIST 17 File exists EXDEV 18 Cross-device link ENODEV 19 Operation not supported by device ENOTDIR 20 Not a directory EISDIR 21 Is a directory EINVAL 22 Invalid argument ENFILE 23 Too many open files in system EMFILE 24 Too many open files ENOTTY 25 Inappropriate ioctl for device ETXTBSY 26 Text file busy EFBIG 27 File too large ENOSPC 28 No space left on device ESPIPE 29 Illegal seek EROFS 30 Read-only file system EMLINK 31 Too many links EPIPE 32 Broken pipe EDOM 33 Numerical argument out of domain ERANGE 34 Result too large EAGAIN 35 Resource temporarily unavailable EWOULDBLOCK 35 Resource temporarily unavailable EINPROGRESS 36 Operation now in progress EALREADY 37 Operation already in progress ENOTSOCK 38 Socket operation on non-socket EDESTADDRREQ 39 Destination address required EMSGSIZE 40 Message too long EPROTOTYPE 41 Protocol wrong type for socket ENOPROTOOPT 42 Protocol not available EPROTONOSUPPORT 43 Protocol not supported ESOCKTNOSUPPORT 44 Socket type not supported ENOTSUP 45 Operation not supported EPFNOSUPPORT 46 Protocol family not supported EAFNOSUPPORT 47 Address family not supported by protocol family EADDRINUSE 48 Address already in use EADDRNOTAVAIL 49 Can`t assign requested address ENETDOWN 50 Network is down ENETUNREACH 51 Network is unreachable ENETRESET 52 Network dropped connection on reset ECONNABORTED 53 Software caused connection abort ECONNRESET 54 Connection reset by peer ENOBUFS 55 No buffer space available EISCONN 56 Socket is already connected ENOTCONN 57 Socket is not connected ESHUTDOWN 58 Can`t send after socket shutdown ETOOMANYREFS 59 Too many references: can`t splice ETIMEDOUT 60 Operation timed out ECONNREFUSED 61 Connection refused ELOOP 62 Too many levels of symbolic links ENAMETOOLONG 63 File name too long EHOSTDOWN 64 Host is down EHOSTUNREACH 65 No route to host ENOTEMPTY 66 Directory not empty EPROCLIM 67 Too many processes EUSERS 68 Too many users EDQUOT 69 Disc quota exceeded ESTALE 70 Stale NFS file handle EREMOTE 71 Too many levels of remote in path EBADRPC 72 RPC struct is bad ERPCMISMATCH 73 RPC version wrong EPROGUNAVAIL 74 RPC prog. not avail EPROGMISMATCH 75 Program version wrong EPROCUNAVAIL 76 Bad procedure for program ENOLCK 77 No locks available ENOSYS 78 Function not implemented EFTYPE 79 Inappropriate file type or format EAUTH 80 Authentication error ENEEDAUTH 81 Need authenticator EPWROFF 82 Device power is off EDEVERR 83 Device error EOVERFLOW 84 Value too large to be stored in data type EBADEXEC 85 Bad executable (or shared library) EBADARCH 86 Bad CPU type in executable ESHLIBVERS 87 Shared library version mismatch EBADMACHO 88 Malformed Mach-o file ECANCELED 89 Operation canceled EIDRM 90 Identifier removed ENOMSG 91 No message of desired type EILSEQ 92 Illegal byte sequence ENOATTR 93 Attribute not found EBADMSG 94 Bad message EMULTIHOP 95 EMULTIHOP (Reserved) ENODATA 96 No message available on STREAM ENOLINK 97 ENOLINK (Reserved) ENOSR 98 No STREAM resources ENOSTR 99 Not a STREAM EPROTO 100 Protocol error ETIME 101 STREAM ioctl timeout EOPNOTSUPP 102 Operation not supported on socket ENOPOLICY 103 Policy not found ENOTRECOVERABLE 104 State not recoverable EOWNERDEAD 105 Previous owner died EQFULL 106 Interface output queue is full ELAST 106 Interface output queue is full 

Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException from!

ErrorCode

The ErrorCode property is the most boring one, as it always returns NativeErrorCode.
.NET Framework, Mono 6.8.0.105:

public override int ErrorCode {  //  // the base class returns the HResult with this property  // we need the Win32 Error Code, hence the override.  //  get {  return NativeErrorCode;  } } 

In .NET Core 3.1.3:

public override int ErrorCode => base.NativeErrorCode; 

Writing cross-platform socket error handling

Circling back to the original method we started this post with, we rewrote ShouldRetryConnection as follows:

protected virtual bool ShouldRetryConnection(Exception ex) {  if (ex is SocketException sx)  return sx.SocketErrorCode == SocketError.ConnectionRefused;  return false; } 

There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.

Overview of the native error codes

In some situations, you may want to have a table with native error codes on different operating systems. We can get these values with the following code snippet:

var allErrors = Enum.GetValues(typeof(SocketError)).Cast<SocketError>().ToList(); var maxNameWidth = allErrors.Select(x => x.ToString().Length).Max(); foreach (var socketError in allErrors) {  var name = socketError.ToString().PadRight(maxNameWidth);  var code = new SocketException((int) socketError).NativeErrorCode.ToString().PadLeft(7);  Console.WriteLine("| {name} | {code} |"); } 

We executed this program on Windows, Linux, and macOS. Here are the aggregated results:

SocketError Windows Linux macOS
Success 0 0 0
OperationAborted 995 125 89
IOPending 997 115 36
Interrupted 10004 4 4
AccessDenied 10013 13 13
Fault 10014 14 14
InvalidArgument 10022 22 22
TooManyOpenSockets 10024 23 23
WouldBlock 10035 11 35
InProgress 10036 115 36
AlreadyInProgress 10037 114 37
NotSocket 10038 88 38
DestinationAddressRequired 10039 89 39
MessageSize 10040 90 40
ProtocolType 10041 91 41
ProtocolOption 10042 92 42
ProtocolNotSupported 10043 93 43
SocketNotSupported 10044 94 44
OperationNotSupported 10045 95 45
ProtocolFamilyNotSupported 10046 96 46
AddressFamilyNotSupported 10047 97 47
AddressAlreadyInUse 10048 98 48
AddressNotAvailable 10049 99 49
NetworkDown 10050 100 50
NetworkUnreachable 10051 101 51
NetworkReset 10052 102 52
ConnectionAborted 10053 103 53
ConnectionReset 10054 104 54
NoBufferSpaceAvailable 10055 105 55
IsConnected 10056 106 56
NotConnected 10057 107 57
Shutdown 10058 32 32
TimedOut 10060 110 60
ConnectionRefused 10061 111 61
HostDown 10064 112 64
HostUnreachable 10065 113 65
ProcessLimit 10067 10067 10067
SystemNotReady 10091 10091 10091
VersionNotSupported 10092 10092 10092
NotInitialized 10093 10093 10093
Disconnecting 10101 108 58
TypeNotFound 10109 10109 10109
HostNotFound 11001 -131073 -131073
TryAgain 11002 11 35
NoRecovery 11003 11003 11003
NoData 11004 61 96
SocketError -1 -1 -1

This table may be useful if you work with native socket error codes.

Summary

From this investigation, we’ve learned the following:

  • SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements always correspond to the Windows socket error codes.
  • SocketException.ErrorCode always returns SocketException.NativeErrorCode.
  • SocketException.NativeErrorCode on .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core, SocketException.NativeErrorCode equals the corresponding native error code from the current operating system.

A few practical recommendations:

  • If you want to write portable code, always use SocketException.SocketErrorCode and compare it with the values of SocketError. Never use raw numerical error codes.
  • If you want to get the native error code on .NET Core (e.g., for passing to another native program), use SocketException.NativeErrorCode. Remember that different Unix-based operating systems (e.g., Linux, macOS, Solaris) have different native code sets. You can get the exact values of the native error codes by using the errno command.

References

  • Microsoft Docs: Windows Sockets Error Codes
  • IBM Knowledge Center: TCP/IP error codes
  • MariaDB: Operating System Error Codes
  • gnu.org: Error Codes
  • Stackoverflow: Identical Error Codes

Содержание

  1. How Socket Error Codes Depend on Runtime and Operating System
  2. Digging into the problem
  3. SocketErrorCode
  4. NativeErrorCode
  5. ErrorCode
  6. Writing cross-platform socket error handling
  7. Overview of the native error codes
  8. Socket Error Перечисление
  9. Определение
  10. Комментарии
  11. Socket. Send Метод
  12. Определение
  13. Перегрузки
  14. Send(Byte[], Int32, Int32, SocketFlags, SocketError)
  15. Параметры
  16. Возвращаемое значение
  17. Исключения
  18. Примеры
  19. Комментарии
  20. См. также раздел
  21. Применяется к
  22. Send(Byte[], Int32, Int32, SocketFlags)
  23. Параметры
  24. Возвращаемое значение
  25. Исключения
  26. Примеры
  27. Комментарии
  28. См. также раздел
  29. Применяется к
  30. Send(ReadOnlySpan , SocketFlags, SocketError)
  31. Параметры
  32. Возвращаемое значение
  33. Исключения
  34. Комментарии
  35. См. также раздел
  36. Применяется к
  37. Send(IList>, SocketFlags, SocketError)
  38. Параметры
  39. Возвращаемое значение
  40. Исключения
  41. Комментарии
  42. Применяется к
  43. Send(Byte[], Int32, SocketFlags)
  44. Параметры
  45. Возвращаемое значение
  46. Исключения
  47. Примеры
  48. Комментарии
  49. См. также раздел
  50. Применяется к
  51. Send(ReadOnlySpan )
  52. Параметры
  53. Возвращаемое значение
  54. Исключения
  55. Комментарии
  56. См. также раздел
  57. Применяется к
  58. Send(IList>, SocketFlags)
  59. Параметры
  60. Возвращаемое значение
  61. Исключения
  62. Комментарии
  63. Применяется к
  64. Send(Byte[], SocketFlags)
  65. Параметры
  66. Возвращаемое значение
  67. Исключения
  68. Примеры
  69. Комментарии

How Socket Error Codes Depend on Runtime and Operating System

Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:

In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException documentation, we will learn that this class has three different properties with error codes:

  • SocketError SocketErrorCode : Gets the error code that is associated with this exception.
  • int ErrorCode : Gets the error code that is associated with this exception.
  • int NativeErrorCode : Gets the Win32 error code associated with this exception.

What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection on .NET Core? Let’s figure it all out!

Digging into the problem

If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:

SocketErrorCode ErrorCode NativeErrorCode
.NET Framework 10061 10061 10061
Mono 10061 10061 10061
.NET Core 10061 10061 10061

10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED ). Now let’s run the same program on Linux:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 111 111

As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode and NativeErrorCode (111). Finally, let’s check macOS:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 61 61

Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode and NativeErrorCode . In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED ):

  • AIX: 79
  • HP-UX: 239
  • Solaris: 146

For a better understanding of what’s going on, let’s check out the source code of all the properties.

SocketErrorCode

These values correspond to the Windows Sockets Error Codes.

NativeErrorCode

In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):

The Windows implementation of GetNativeErrorForSocketError is trivial (see SocketException.Windows.cs):

The Unix implementation is more complicated (see SocketException.Unix.cs):

TryGetNativeErrorForSocketError should convert SocketError to the native Unix error code. Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):

Once we have an instance of Interop.Error , we call interopErr.Info().RawErrno . The implementation of RawErrno can be found in Interop.Errors.cs:

Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:

Note that errno may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils to get this utility. Here is a typical output on macOS:

Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException from!

ErrorCode

Writing cross-platform socket error handling

There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.

Overview of the native error codes

We executed this program on Windows, Linux, and macOS. Here are the aggregated results:

Источник

Определение

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Определяет коды ошибок для класса Socket.

Предпринята попытка получить доступ к объекту Socket способом, запрещенным его правами доступа.

Обычно разрешается использовать только адрес.

AddressFamilyNotSupported 10047

Указанное семейство адресов не поддерживается. Эта ошибка возвращается, если указано семейство IPv6-адресов, а стек протокола IPv6 не установлен на локальном компьютере. Эта ошибка возвращается, если указано семейство IPv4-адресов, а стек протокола IPv4 не установлен на локальном компьютере.

Выбранный IP-адрес является недопустимым в этом контексте.

На незаблокированном сокете Socket уже выполняется операция.

Подключение разорвано платформой .NET или поставщиком основного сокета.

Удаленный узел активно отказывает в подключении.

Подключение сброшено удаленным компьютером.

DestinationAddressRequired 10039

В операции на сокете Socket пропущен обязательный адрес.

Выполняется правильная последовательность отключения.

Поставщиком основного сокета обнаружен недопустимый указатель адреса.

Ошибка при выполнении операции, вызванная отключением удаленного узла.

Такой узел не существует. Данное имя не является ни официальным именем узла, ни псевдонимом.

Отсутствует сетевой маршрут к указанному узлу.

Выполняется блокирующая операция.

Вызов к заблокированному сокету Socketбыл отменен.

Предоставлен недопустимый аргумент для члена объекта Socket.

Приложение инициировало перекрывающуюся операцию, которая не может быть закончена немедленно.

Объект Socket уже подключен.

У датаграммы слишком большая длина.

Приложение пытается задать значение KeepAlive для подключения, которое уже отключено.

Не существует маршрута к удаленному узлу.

Отсутствует свободное буферное пространство для операции объекта Socket.

Требуемое имя или IP-адрес не найдены на сервере имен.

Неустранимая ошибка, или не удается найти запрошенную базу данных.

Приложение пытается отправить или получить данные, а объект Socket не подключен.

Основной поставщик сокета не инициализирован.

Предпринята попытка выполнить операцию объекта Socket не на сокете.

Перекрывающаяся операция была прервана из-за закрытия объекта Socket.

Семейство адресов не поддерживается семейством протоколов.

Слишком много процессов используется основным поставщиком сокета.

ProtocolFamilyNotSupported 10046

Семейство протоколов не реализовано или не настроено.

Протокол не реализован или не настроен.

Для объекта Socket был использован неизвестный, недопустимый или неподдерживаемый параметр или уровень.

Неверный тип протокола для данного объекта Socket.

Запрос на отправку или получение данных отклонен, так как объект Socket уже закрыт.

Произошла неопознанная ошибка объекта Socket.

Указанный тип сокета не поддерживается в данном семействе адресов.

Операция Socket выполнена успешно.

Подсистема сети недоступна.

Истекло время ожидания попытки подключения, или произошел сбой при отклике подключенного узла.

Слишком много открытых сокетов в основном поставщике сокета.

Не удалось разрешить имя узла. Повторите попытку позже.

Указанный класс не найден.

Версия основного поставщика сокета выходит за пределы допустимого диапазона.

Операция на незаблокированном сокете не может быть закончена немедленно.

Комментарии

Большинство из этих ошибок возвращается базовым поставщиком сокета.

Источник

Socket. Send Метод

Определение

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Передает данные в подключенный объект Socket.

Перегрузки

Отправляет указанное количество байтов данных в подключенный Socket, начиная с заданного смещения и используя заданный параметр SocketFlags.

Отправляет указанное количество байтов данных в подключенный Socket, начиная с заданного смещения и используя заданный параметр SocketFlags.

Передает данные в подключенный объект Socket, используя заданный объект SocketFlags.

Отправляет набор буферов в список на подключенный объект Socket, используя указанный объект SocketFlags.

Посылает указанное число байтов данных на подключенный объект Socket, используя заданный объект SocketFlags.

Передает данные в подключенный объект Socket.

Отправляет набор буферов в список на подключенный объект Socket, используя указанный объект SocketFlags.

Передает данные в подключенный объект Socket, используя заданный объект SocketFlags.

Передает данные в подключенный объект Socket, используя заданный объект SocketFlags.

Отправляет набор буферов в список на подключенный объект Socket.

Передает данные в подключенный объект Socket.

Send(Byte[], Int32, Int32, SocketFlags, SocketError)

Отправляет указанное количество байтов данных в подключенный Socket, начиная с заданного смещения и используя заданный параметр SocketFlags.

Параметры

Массив типа Byte, содержащий данные для отправки.

Положение в буфере данных, с которого начинается отправка данных.

Количество байтов для отправки.

Поразрядное сочетание значений SocketFlags.

Объект SocketError, содержащий ошибку сокета.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffer имеет значение null .

Значение параметра offset меньше 0.

Значение offset превышает длину buffer .

Значение параметра size меньше 0.

Значение size превышает значение, полученное, если отнять от длины buffer значение параметра offset .

socketFlags — недопустимое сочетание значений.

Произошла ошибка операционной системы при доступе к Socket.

Примеры

В следующем примере кода указывается буфер данных, смещение, размер и SocketFlags для отправки данных в подключенный Socketобъект .

Комментарии

Send синхронно отправляет данные на удаленный узел, указанный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Если в этой перегрузке DontRoute указать флаг в socketflags качестве параметра, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода Send или вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать для Connect установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo. Если вы не используете SendTo, вам придется вызывать Connect перед каждым вызовом Send. Можно использовать SendTo даже после установки удаленного узла по умолчанию с Connect. Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Кроме того, необходимо убедиться, что размер не превышает максимальный размер пакета базового поставщика услуг. В этом случае датаграмма не будет отправлена и Send вызовет исключение SocketException.

Если вы используете протокол, ориентированный на подключение, Send будет блокироваться до отправки запрошенного количества байтов, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме неблокировки может успешно завершиться, Send даже если отправляется меньше запрашиваемых байтов. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит запрошенное количество байтов. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу, пока не будет собран значительный объем исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, ознакомьтесь с документацией по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка блокируется, если сокет не был помещен в неблокировочный режим.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

См. также раздел

Применяется к

Send(Byte[], Int32, Int32, SocketFlags)

Отправляет указанное количество байтов данных в подключенный Socket, начиная с заданного смещения и используя заданный параметр SocketFlags.

Параметры

Массив типа Byte, содержащий данные для отправки.

Положение в буфере данных, с которого начинается отправка данных.

Количество байтов для отправки.

Поразрядное сочетание значений SocketFlags.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffer имеет значение null .

Значение параметра offset меньше 0.

Значение offset превышает длину buffer .

Значение параметра size меньше 0.

Значение size превышает значение, полученное, если отнять от длины buffer значение параметра offset .

socketFlags — недопустимое сочетание значений.

Произошла ошибка операционной системы при доступе к Socket.

Примеры

В следующем примере кода указывается буфер данных, смещение, размер и SocketFlags для отправки данных в подключенный Socketобъект .

Комментарии

Send синхронно отправляет данные на удаленный узел, указанный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Если в этой перегрузке DontRoute указать флаг в socketflags качестве параметра, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода Send или вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать для Connect установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo. Если вы не используете SendTo, вам придется вызывать Connect перед каждым вызовом Send. Можно использовать SendTo даже после установки удаленного узла по умолчанию с Connect. Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Кроме того, необходимо убедиться, что размер не превышает максимальный размер пакета базового поставщика услуг. В этом случае датаграмма не будет отправлена и Send вызовет исключение SocketException.

Если вы используете протокол, ориентированный на подключение, Send будет блокироваться до отправки запрошенного количества байтов, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме неблокировки может успешно завершиться, Send даже если отправляется меньше запрашиваемых байтов. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит запрошенное количество байтов. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу, пока не будет собран значительный объем исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, ознакомьтесь с документацией по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка блокируется, если сокет не был помещен в неблокировочный режим.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

См. также раздел

Применяется к

Send(ReadOnlySpan , SocketFlags, SocketError)

Передает данные в подключенный объект Socket, используя заданный объект SocketFlags.

Параметры

Диапазон байтов, содержащий отправляемые данные.

Побитовое сочетание значений перечисления, которое задает поведение получения и отправки.

При возврате из этого метода содержит одно из значений перечисления, которое определяет коды ошибок для сокета.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

Произошла ошибка при попытке доступа к сокету.

Комментарии

Send синхронно отправляет данные на удаленный узел, указанный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Для этой перегрузки требуется буфер, содержащий данные, которые требуется отправить. Значение SocketFlags по умолчанию равно 0, смещение буфера по умолчанию равно 0, а количество отправляемых байтов по умолчанию равно размеру буфера.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода или Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать Connect для установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если вы не используете SendTo метод , вам придется вызывать Connect перед каждым вызовом Send. Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Если вы используете протокол, ориентированный на подключение, будет блокироваться, Send пока не будут отправлены все байты в буфере, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме неблокировки может успешно завершиться, Send даже если отправляется меньше байтов в буфере. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит байты в буфер. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу, пока не будет собран значительный объем исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, ознакомьтесь с документацией по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка блокируется, если сокет не был помещен в неблокировочный режим.

См. также раздел

Применяется к

Send(IList>, SocketFlags, SocketError)

Этот API несовместим с CLS.

Отправляет набор буферов в список на подключенный объект Socket, используя указанный объект SocketFlags.

Параметры

Список объектов ArraySegment типа Byte, содержащих данные для отправки.

Поразрядное сочетание значений SocketFlags.

Объект SocketError, содержащий ошибку сокета.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffers имеет значение null .

Параметр buffers пуст.

Произошла ошибка при попытке доступа к сокету.

Комментарии

Для этой перегрузки требуется по крайней мере один буфер, содержащий данные, которые требуется отправить. Значение SocketFlags по умолчанию равно 0. Если в качестве socketFlags параметра указать DontRoute флаг, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода или Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать для Connect установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если метод не используется SendTo , необходимо вызывать Connect перед каждым вызовом Send. Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Если вы используете протокол, ориентированный на подключение, Send будет блокироваться, пока не будут отправлены все байты в буфере, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме без блокировки может завершиться успешно, Send даже если отправляется меньше байтов в буфере. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит байты в буфер. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу, пока не будет собран значительный объем исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, ознакомьтесь с документацией по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка блокируется, если сокет не был помещен в неблокировочный режим.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Применяется к

Send(Byte[], Int32, SocketFlags)

Посылает указанное число байтов данных на подключенный объект Socket, используя заданный объект SocketFlags.

Параметры

Массив типа Byte, содержащий данные для отправки.

Количество байтов для отправки.

Поразрядное сочетание значений SocketFlags.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffer имеет значение null .

Значение параметра size меньше 0 или превышает размер буфера.

socketFlags — недопустимое сочетание значений.

Сбой операционной системы при доступе к сокету.

Примеры

В следующем примере кода отправляется данные, найденные в буфере, и указывается None для SocketFlags.

Комментарии

Send синхронно отправляет данные на удаленный узел, установленный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Для этой перегрузки требуется буфер, содержащий данные, которые требуется отправить, количество байтов, которые требуется отправить, и побитовое сочетание любых SocketFlags. Если в качестве socketflags параметра указать DontRoute флаг, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода или Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать Connect для установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если вы не используете SendTo метод , необходимо вызывать Connect метод перед каждым вызовом Send метода . Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

При использовании протокола, ориентированного на подключение, блокируется до Send отправки запрошенного количества байтов, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме без блокировки может успешно завершиться, Send даже если отправляется меньше запрашиваемого количества байтов. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит запрошенное количество байтов. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу до сбора значительного объема исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Необходимо убедиться, что размер не превышает максимальный размер пакета базового поставщика услуг. В этом случае датаграмма не будет отправлена и Send вызовет исключение SocketException. Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, подробное описание ошибки см. в документации по коду ошибок API сокетов Windows версии 2 .

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка будет блокироваться, если сокет не был помещен в неблокировочный режим.

См. также раздел

Применяется к

Send(ReadOnlySpan )

Передает данные в подключенный объект Socket.

Параметры

Диапазон байтов, содержащий отправляемые данные.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

Произошла ошибка при попытке доступа к сокету.

Комментарии

Send синхронно отправляет данные на удаленный узел, указанный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Для этой перегрузки требуется буфер, содержащий данные, которые вы хотите отправить. Значение SocketFlags по умолчанию равно 0, смещение буфера по умолчанию равно 0, а число отправляемых байтов по умолчанию равно размеру буфера.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода или Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать Connect для установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если вы не используете SendTo метод , вам придется вызывать Connect перед каждым вызовом Sendметода . Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Если вы используете протокол, ориентированный на подключение, Send будет блокироваться до отправки всех байтов в буфере, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме без блокировки может успешно завершиться, Send даже если отправляется меньше, чем количество байтов в буфере. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит байты в буфер. Кроме того, нет никакой гарантии, что отправляемые данные появятся в сети немедленно. Чтобы повысить эффективность сети, базовая система может отложить передачу до сбора значительного объема исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, подробное описание ошибки см. в документации по коду ошибок API сокетов Windows версии 2 .

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка будет блокироваться, если сокет не был помещен в неблокировочный режим.

См. также раздел

Применяется к

Send(IList>, SocketFlags)

Отправляет набор буферов в список на подключенный объект Socket, используя указанный объект SocketFlags.

Параметры

Список объектов ArraySegment типа Byte, содержащих данные для отправки.

Поразрядное сочетание значений SocketFlags.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffers имеет значение null .

Параметр buffers пуст.

Произошла ошибка при попытке доступа к сокету.

Комментарии

Для этой перегрузки требуется по крайней мере один буфер, содержащий отправляемые данные. Значение SocketFlags по умолчанию равно 0. Если указать DontRoute флаг в socketFlags качестве параметра, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода, иначе Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать Connect для установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если метод не используется SendTo , необходимо вызывать Connect перед каждым вызовом Sendметода . Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовомSend, выполнив еще один вызов .Connect

Если вы используете протокол, ориентированный на подключение, будет блокироваться до тех пор, Send пока не будут отправлены все байты в буфере, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме без блокировки может успешно завершиться, Send даже если отправляется меньше, чем количество байтов в буфере. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит байты в буфер. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу до сбора значительного объема исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, подробное описание ошибки см. в документации по коду ошибок API сокетов Windows версии 2 .

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка будет блокироваться, если сокет не был помещен в неблокировочный режим.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Применяется к

Send(Byte[], SocketFlags)

Передает данные в подключенный объект Socket, используя заданный объект SocketFlags.

Параметры

Массив типа Byte, содержащий данные для отправки.

Поразрядное сочетание значений SocketFlags.

Возвращаемое значение

Количество байтов, отправленных в Socket.

Исключения

buffer имеет значение null .

Произошла ошибка при попытке доступа к сокету.

Примеры

В следующем примере кода демонстрируется отправка данных на подключенный Socketобъект .

Комментарии

Send синхронно отправляет данные на удаленный узел, установленный в методе Connect или , Accept и возвращает количество успешно отправленных байтов. Метод Send можно использовать как для протоколов, ориентированных на подключение, так и для протоколов без подключения.

Для этой перегрузки требуется буфер, содержащий данные, которые требуется отправить, и побитовое сочетание SocketFlags. Смещение буфера по умолчанию равны 0, а число отправляемых байтов — по умолчанию к размеру буфера. Если указать DontRoute флаг в socketflags качестве значения параметра, отправляемые данные не будут перенаправлены.

Если вы используете протокол без подключения, необходимо вызвать Connect перед вызовом SocketExceptionэтого метода, иначе Send вызовет исключение . Если вы используете протокол, ориентированный на подключение, необходимо либо использовать для Connect установки подключения к удаленному узлу, либо использовать для Accept принятия входящего подключения.

Если вы используете протокол без подключения и планируете отправлять данные на несколько разных узлов, следует использовать SendTo метод . Если метод не используется SendTo , необходимо вызывать метод перед каждым вызовом ConnectSendметода . Вы можете использовать SendTo даже после установки удаленного узла по умолчанию с Connectпомощью . Вы также можете изменить удаленный узел по умолчанию перед вызовом Send , выполнив еще один вызов Connect.

Если вы используете протокол, ориентированный на подключение, Send будет блокироваться, пока не будут отправлены все байты в буфере, если время ожидания не было задано с помощью Socket.SendTimeout. Если превышено время ожидания, Send вызов вызовет исключение SocketException. В режиме неблокировки может успешно завершиться, Send даже если отправляется меньше байтов в буфере. Ваше приложение отвечает за отслеживание количества отправленных байтов и повторение операции до тех пор, пока приложение не отправит запрошенное количество байтов. Кроме того, нет никакой гарантии, что отправляемые данные сразу же появятся в сети. Чтобы повысить эффективность сети, базовая система может отложить передачу, пока не будет собран значительный объем исходящих данных. Успешное завершение Send метода означает, что в базовой системе есть место для буферизации данных для отправки по сети.

Необходимо убедиться, что размер буфера не превышает максимальный размер пакета базового поставщика услуг. В этом случае датаграмма не будет отправлена и Send вызовет исключение SocketException. Если вы получаете SocketException, используйте SocketException.ErrorCode свойство , чтобы получить конкретный код ошибки. Получив этот код, ознакомьтесь с документацией по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Успешное завершение отправки не означает, что данные были успешно доставлены. Если в транспортной системе нет буферного пространства для хранения передаваемых данных, отправка блокируется, если сокет не был помещен в неблокировочный режим.

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в статье Трассировка сети в платформа .NET Framework.

Источник

Dotnet logo

Dev Team blog

How Socket Error Codes Depend on Runtime and Operating System

This post is the first part of a blog post series that covers different technical challenges that we had to resolve during the migration of the Rider backend process from Mono to .NET Core. By sharing our experiences, we hope to help out those who are in the same boat.
There’s too much to share in one post, so we will make this into a series of posts. In this series:

  • How Socket Error Codes Depend on Runtime and Operating System
  • How Sorting Order Depends on Runtime and Operating System
  • How ListSeparator Depends on Runtime and Operating System

Let’s dive in!

Sockets and error codes

Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:

protected virtual bool ShouldRetryConnection (Exception ex, int attemptNumber)
{
    var sx = ex as SocketException;
    if (sx != null) {
        if (sx.ErrorCode == 10061) //connection refused
            return true;
    }
    return false;
}

In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException documentation, we will learn that this class has three different properties with error codes:

  • SocketError SocketErrorCode: Gets the error code that is associated with this exception.
  • int ErrorCode: Gets the error code that is associated with this exception.
  • int NativeErrorCode: Gets the Win32 error code associated with this exception.

What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection on .NET Core? Let’s figure it all out!

Digging into the problem

Let’s start with the following program, which prints error code property values for SocketError.ConnectionRefused:

var se = new SocketException((int) SocketError.ConnectionRefused);
Console.WriteLine((int)se.SocketErrorCode);
Console.WriteLine(se.ErrorCode);
Console.WriteLine(se.NativeErrorCode);

If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:

SocketErrorCode ErrorCode NativeErrorCode
.NET Framework 10061 10061 10061
Mono 10061 10061 10061
.NET Core 10061 10061 10061

10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED).
Now let’s run the same program on Linux:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 111 111

As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode and NativeErrorCode (111).
Finally, let’s check macOS:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 61 61

Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode and NativeErrorCode.
In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED):

  • AIX: 79
  • HP-UX: 239
  • Solaris: 146

For a better understanding of what’s going on, let’s check out the source code of all the properties.

SocketErrorCode

SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements are the same on all the runtimes (see its implementation in .NET Framework, .NET Core 3.1.3, and Mono 6.8.0.105):

public enum SocketError
{
    SocketError = -1, // 0xFFFFFFFF
    Success = 0,
    OperationAborted = 995, // 0x000003E3
    IOPending = 997, // 0x000003E5
    Interrupted = 10004, // 0x00002714
    AccessDenied = 10013, // 0x0000271D
    Fault = 10014, // 0x0000271E
    InvalidArgument = 10022, // 0x00002726
    TooManyOpenSockets = 10024, // 0x00002728
    WouldBlock = 10035, // 0x00002733
    InProgress = 10036, // 0x00002734
    AlreadyInProgress = 10037, // 0x00002735
    NotSocket = 10038, // 0x00002736
    DestinationAddressRequired = 10039, // 0x00002737
    MessageSize = 10040, // 0x00002738
    ProtocolType = 10041, // 0x00002739
    ProtocolOption = 10042, // 0x0000273A
    ProtocolNotSupported = 10043, // 0x0000273B
    SocketNotSupported = 10044, // 0x0000273C
    OperationNotSupported = 10045, // 0x0000273D
    ProtocolFamilyNotSupported = 10046, // 0x0000273E
    AddressFamilyNotSupported = 10047, // 0x0000273F
    AddressAlreadyInUse = 10048, // 0x00002740
    AddressNotAvailable = 10049, // 0x00002741
    NetworkDown = 10050, // 0x00002742
    NetworkUnreachable = 10051, // 0x00002743
    NetworkReset = 10052, // 0x00002744
    ConnectionAborted = 10053, // 0x00002745
    ConnectionReset = 10054, // 0x00002746
    NoBufferSpaceAvailable = 10055, // 0x00002747
    IsConnected = 10056, // 0x00002748
    NotConnected = 10057, // 0x00002749
    Shutdown = 10058, // 0x0000274A
    TimedOut = 10060, // 0x0000274C
    ConnectionRefused = 10061, // 0x0000274D
    HostDown = 10064, // 0x00002750
    HostUnreachable = 10065, // 0x00002751
    ProcessLimit = 10067, // 0x00002753
    SystemNotReady = 10091, // 0x0000276B
    VersionNotSupported = 10092, // 0x0000276C
    NotInitialized = 10093, // 0x0000276D
    Disconnecting = 10101, // 0x00002775
    TypeNotFound = 10109, // 0x0000277D
    HostNotFound = 11001, // 0x00002AF9
    TryAgain = 11002, // 0x00002AFA
    NoRecovery = 11003, // 0x00002AFB
    NoData = 11004, // 0x00002AFC
}

These values correspond to the Windows Sockets Error Codes.

NativeErrorCode

In .NET Framework and Mono, SocketErrorCode and NativeErrorCode always have the same values:

public SocketError SocketErrorCode {
    //
    // the base class returns the HResult with this property
    // we need the Win32 Error Code, hence the override.
    //
    get {
        return (SocketError)NativeErrorCode;
    }
}

In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):

public SocketException(int errorCode) : this((SocketError)errorCode)
// ...
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))

The Windows implementation of GetNativeErrorForSocketError is trivial (see SocketException.Windows.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    // SocketError values map directly to Win32 error codes
    return (int)error;
}

The Unix implementation is more complicated (see SocketException.Unix.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    int nativeErr = (int)error;
    if (error != SocketError.SocketError)
    {
        Interop.Error interopErr;

        // If an interop error was not found, then don't invoke Info().RawErrno as that will fail with assert.
        if (SocketErrorPal.TryGetNativeErrorForSocketError(error, out interopErr))
        {
            nativeErr = interopErr.Info().RawErrno;
        }
    }

    return nativeErr;
}

TryGetNativeErrorForSocketError should convert SocketError to the native Unix error code.
Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):

private const int NativeErrorToSocketErrorCount = 42;
private const int SocketErrorToNativeErrorCount = 40;

// No Interop.Errors are included for the following SocketErrors, as there's no good mapping:
// - SocketError.NoRecovery
// - SocketError.NotInitialized
// - SocketError.ProcessLimit
// - SocketError.SocketError
// - SocketError.SystemNotReady
// - SocketError.TypeNotFound
// - SocketError.VersionNotSupported

private static readonly Dictionary<Interop.Error, SocketError> s_nativeErrorToSocketError = new Dictionary<Interop.Error, SocketError>(NativeErrorToSocketErrorCount)
{
    { Interop.Error.EACCES, SocketError.AccessDenied },
    { Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse },
    { Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable },
    { Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported },
    { Interop.Error.EAGAIN, SocketError.WouldBlock },
    { Interop.Error.EALREADY, SocketError.AlreadyInProgress },
    { Interop.Error.EBADF, SocketError.OperationAborted },
    { Interop.Error.ECANCELED, SocketError.OperationAborted },
    { Interop.Error.ECONNABORTED, SocketError.ConnectionAborted },
    { Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused },
    { Interop.Error.ECONNRESET, SocketError.ConnectionReset },
    { Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired },
    { Interop.Error.EFAULT, SocketError.Fault },
    { Interop.Error.EHOSTDOWN, SocketError.HostDown },
    { Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available
    { Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable },
    { Interop.Error.EINPROGRESS, SocketError.InProgress },
    { Interop.Error.EINTR, SocketError.Interrupted },
    { Interop.Error.EINVAL, SocketError.InvalidArgument },
    { Interop.Error.EISCONN, SocketError.IsConnected },
    { Interop.Error.EMFILE, SocketError.TooManyOpenSockets },
    { Interop.Error.EMSGSIZE, SocketError.MessageSize },
    { Interop.Error.ENETDOWN, SocketError.NetworkDown },
    { Interop.Error.ENETRESET, SocketError.NetworkReset },
    { Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable },
    { Interop.Error.ENFILE, SocketError.TooManyOpenSockets },
    { Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable },
    { Interop.Error.ENODATA, SocketError.NoData },
    { Interop.Error.ENOENT, SocketError.AddressNotAvailable },
    { Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption },
    { Interop.Error.ENOTCONN, SocketError.NotConnected },
    { Interop.Error.ENOTSOCK, SocketError.NotSocket },
    { Interop.Error.ENOTSUP, SocketError.OperationNotSupported },
    { Interop.Error.EPERM, SocketError.AccessDenied },
    { Interop.Error.EPIPE, SocketError.Shutdown },
    { Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported },
    { Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported },
    { Interop.Error.EPROTOTYPE, SocketError.ProtocolType },
    { Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported },
    { Interop.Error.ESHUTDOWN, SocketError.Disconnecting },
    { Interop.Error.SUCCESS, SocketError.Success },
    { Interop.Error.ETIMEDOUT, SocketError.TimedOut },
};

private static readonly Dictionary<SocketError, Interop.Error> s_socketErrorToNativeError = new Dictionary<SocketError, Interop.Error>(SocketErrorToNativeErrorCount)
{
    // This is *mostly* an inverse mapping of s_nativeErrorToSocketError.  However, some options have multiple mappings and thus
    // can't be inverted directly.  Other options don't have a mapping from native to SocketError, but when presented with a SocketError,
    // we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but
    // SocketError.IOPending also maps closest to EINPROGRESS.  As such, roundtripping won't necessarily provide the original value 100% of the time,
    // but it's the best we can do given the mismatch between Interop.Error and SocketError.

    { SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM
    { SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE  },
    { SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL },
    { SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT  },
    { SocketError.AlreadyInProgress, Interop.Error.EALREADY },
    { SocketError.ConnectionAborted, Interop.Error.ECONNABORTED },
    { SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED },
    { SocketError.ConnectionReset, Interop.Error.ECONNRESET },
    { SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ },
    { SocketError.Disconnecting, Interop.Error.ESHUTDOWN },
    { SocketError.Fault, Interop.Error.EFAULT },
    { SocketError.HostDown, Interop.Error.EHOSTDOWN },
    { SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND },
    { SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH },
    { SocketError.InProgress, Interop.Error.EINPROGRESS },
    { SocketError.Interrupted, Interop.Error.EINTR },
    { SocketError.InvalidArgument, Interop.Error.EINVAL },
    { SocketError.IOPending, Interop.Error.EINPROGRESS },
    { SocketError.IsConnected, Interop.Error.EISCONN },
    { SocketError.MessageSize, Interop.Error.EMSGSIZE },
    { SocketError.NetworkDown, Interop.Error.ENETDOWN },
    { SocketError.NetworkReset, Interop.Error.ENETRESET },
    { SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH },
    { SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS },
    { SocketError.NoData, Interop.Error.ENODATA },
    { SocketError.NotConnected, Interop.Error.ENOTCONN },
    { SocketError.NotSocket, Interop.Error.ENOTSOCK },
    { SocketError.OperationAborted, Interop.Error.ECANCELED },
    { SocketError.OperationNotSupported, Interop.Error.ENOTSUP },
    { SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT },
    { SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT },
    { SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT },
    { SocketError.ProtocolType, Interop.Error.EPROTOTYPE },
    { SocketError.Shutdown, Interop.Error.EPIPE },
    { SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT },
    { SocketError.Success, Interop.Error.SUCCESS },
    { SocketError.TimedOut, Interop.Error.ETIMEDOUT },
    { SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE
    { SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing
    { SocketError.WouldBlock, Interop.Error.EAGAIN  },
};

internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno)
{
    return s_socketErrorToNativeError.TryGetValue(error, out errno);
}

Once we have an instance of Interop.Error, we call interopErr.Info().RawErrno. The implementation of RawErrno can be found in Interop.Errors.cs:

internal int RawErrno
{
    get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
}

[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")]
internal static extern int ConvertErrorPalToPlatform(Error error);

Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:

$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 No such device or address
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EAGAIN 11 Resource temporarily unavailable
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Device or resource busy
EEXIST 17 File exists
EXDEV 18 Invalid cross-device link
ENODEV 19 No such device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Numerical result out of range
EDEADLK 35 Resource deadlock avoided
ENAMETOOLONG 36 File name too long
ENOLCK 37 No locks available
ENOSYS 38 Function not implemented
ENOTEMPTY 39 Directory not empty
ELOOP 40 Too many levels of symbolic links
EWOULDBLOCK 11 Resource temporarily unavailable
ENOMSG 42 No message of desired type
EIDRM 43 Identifier removed
ECHRNG 44 Channel number out of range
EL2NSYNC 45 Level 2 not synchronized
EL3HLT 46 Level 3 halted
EL3RST 47 Level 3 reset
ELNRNG 48 Link number out of range
EUNATCH 49 Protocol driver not attached
ENOCSI 50 No CSI structure available
EL2HLT 51 Level 2 halted
EBADE 52 Invalid exchange
EBADR 53 Invalid request descriptor
EXFULL 54 Exchange full
ENOANO 55 No anode
EBADRQC 56 Invalid request code
EBADSLT 57 Invalid slot
EDEADLOCK 35 Resource deadlock avoided
EBFONT 59 Bad font file format
ENOSTR 60 Device not a stream
ENODATA 61 No data available
ETIME 62 Timer expired
ENOSR 63 Out of streams resources
ENONET 64 Machine is not on the network
ENOPKG 65 Package not installed
EREMOTE 66 Object is remote
ENOLINK 67 Link has been severed
EADV 68 Advertise error
ESRMNT 69 Srmount error
ECOMM 70 Communication error on send
EPROTO 71 Protocol error
EMULTIHOP 72 Multihop attempted
EDOTDOT 73 RFS specific error
EBADMSG 74 Bad message
EOVERFLOW 75 Value too large for defined data type
ENOTUNIQ 76 Name not unique on network
EBADFD 77 File descriptor in bad state
EREMCHG 78 Remote address changed
ELIBACC 79 Can not access a needed shared library
ELIBBAD 80 Accessing a corrupted shared library
ELIBSCN 81 .lib section in a.out corrupted
ELIBMAX 82 Attempting to link in too many shared libraries
ELIBEXEC 83 Cannot exec a shared library directly
EILSEQ 84 Invalid or incomplete multibyte or wide character
ERESTART 85 Interrupted system call should be restarted
ESTRPIPE 86 Streams pipe error
EUSERS 87 Too many users
ENOTSOCK 88 Socket operation on non-socket
EDESTADDRREQ 89 Destination address required
EMSGSIZE 90 Message too long
EPROTOTYPE 91 Protocol wrong type for socket
ENOPROTOOPT 92 Protocol not available
EPROTONOSUPPORT 93 Protocol not supported
ESOCKTNOSUPPORT 94 Socket type not supported
EOPNOTSUPP 95 Operation not supported
EPFNOSUPPORT 96 Protocol family not supported
EAFNOSUPPORT 97 Address family not supported by protocol
EADDRINUSE 98 Address already in use
EADDRNOTAVAIL 99 Cannot assign requested address
ENETDOWN 100 Network is down
ENETUNREACH 101 Network is unreachable
ENETRESET 102 Network dropped connection on reset
ECONNABORTED 103 Software caused connection abort
ECONNRESET 104 Connection reset by peer
ENOBUFS 105 No buffer space available
EISCONN 106 Transport endpoint is already connected
ENOTCONN 107 Transport endpoint is not connected
ESHUTDOWN 108 Cannot send after transport endpoint shutdown
ETOOMANYREFS 109 Too many references: cannot splice
ETIMEDOUT 110 Connection timed out
ECONNREFUSED 111 Connection refused
EHOSTDOWN 112 Host is down
EHOSTUNREACH 113 No route to host
EALREADY 114 Operation already in progress
EINPROGRESS 115 Operation now in progress
ESTALE 116 Stale file handle
EUCLEAN 117 Structure needs cleaning
ENOTNAM 118 Not a XENIX named type file
ENAVAIL 119 No XENIX semaphores available
EISNAM 120 Is a named type file
EREMOTEIO 121 Remote I/O error
EDQUOT 122 Disk quota exceeded
ENOMEDIUM 123 No medium found
EMEDIUMTYPE 124 Wrong medium type
ECANCELED 125 Operation canceled
ENOKEY 126 Required key not available
EKEYEXPIRED 127 Key has expired
EKEYREVOKED 128 Key has been revoked
EKEYREJECTED 129 Key was rejected by service
EOWNERDEAD 130 Owner died
ENOTRECOVERABLE 131 State not recoverable
ERFKILL 132 Operation not possible due to RF-kill
EHWPOISON 133 Memory page has hardware error
ENOTSUP 95 Operation not supported

Note that errno may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils to get this utility.
Here is a typical output on macOS:

$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 Device not configured
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EDEADLK 11 Resource deadlock avoided
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Resource busy
EEXIST 17 File exists
EXDEV 18 Cross-device link
ENODEV 19 Operation not supported by device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Result too large
EAGAIN 35 Resource temporarily unavailable
EWOULDBLOCK 35 Resource temporarily unavailable
EINPROGRESS 36 Operation now in progress
EALREADY 37 Operation already in progress
ENOTSOCK 38 Socket operation on non-socket
EDESTADDRREQ 39 Destination address required
EMSGSIZE 40 Message too long
EPROTOTYPE 41 Protocol wrong type for socket
ENOPROTOOPT 42 Protocol not available
EPROTONOSUPPORT 43 Protocol not supported
ESOCKTNOSUPPORT 44 Socket type not supported
ENOTSUP 45 Operation not supported
EPFNOSUPPORT 46 Protocol family not supported
EAFNOSUPPORT 47 Address family not supported by protocol family
EADDRINUSE 48 Address already in use
EADDRNOTAVAIL 49 Can`t assign requested address
ENETDOWN 50 Network is down
ENETUNREACH 51 Network is unreachable
ENETRESET 52 Network dropped connection on reset
ECONNABORTED 53 Software caused connection abort
ECONNRESET 54 Connection reset by peer
ENOBUFS 55 No buffer space available
EISCONN 56 Socket is already connected
ENOTCONN 57 Socket is not connected
ESHUTDOWN 58 Can`t send after socket shutdown
ETOOMANYREFS 59 Too many references: can`t splice
ETIMEDOUT 60 Operation timed out
ECONNREFUSED 61 Connection refused
ELOOP 62 Too many levels of symbolic links
ENAMETOOLONG 63 File name too long
EHOSTDOWN 64 Host is down
EHOSTUNREACH 65 No route to host
ENOTEMPTY 66 Directory not empty
EPROCLIM 67 Too many processes
EUSERS 68 Too many users
EDQUOT 69 Disc quota exceeded
ESTALE 70 Stale NFS file handle
EREMOTE 71 Too many levels of remote in path
EBADRPC 72 RPC struct is bad
ERPCMISMATCH 73 RPC version wrong
EPROGUNAVAIL 74 RPC prog. not avail
EPROGMISMATCH 75 Program version wrong
EPROCUNAVAIL 76 Bad procedure for program
ENOLCK 77 No locks available
ENOSYS 78 Function not implemented
EFTYPE 79 Inappropriate file type or format
EAUTH 80 Authentication error
ENEEDAUTH 81 Need authenticator
EPWROFF 82 Device power is off
EDEVERR 83 Device error
EOVERFLOW 84 Value too large to be stored in data type
EBADEXEC 85 Bad executable (or shared library)
EBADARCH 86 Bad CPU type in executable
ESHLIBVERS 87 Shared library version mismatch
EBADMACHO 88 Malformed Mach-o file
ECANCELED 89 Operation canceled
EIDRM 90 Identifier removed
ENOMSG 91 No message of desired type
EILSEQ 92 Illegal byte sequence
ENOATTR 93 Attribute not found
EBADMSG 94 Bad message
EMULTIHOP 95 EMULTIHOP (Reserved)
ENODATA 96 No message available on STREAM
ENOLINK 97 ENOLINK (Reserved)
ENOSR 98 No STREAM resources
ENOSTR 99 Not a STREAM
EPROTO 100 Protocol error
ETIME 101 STREAM ioctl timeout
EOPNOTSUPP 102 Operation not supported on socket
ENOPOLICY 103 Policy not found
ENOTRECOVERABLE 104 State not recoverable
EOWNERDEAD 105 Previous owner died
EQFULL 106 Interface output queue is full
ELAST 106 Interface output queue is full

Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException from!

ErrorCode

The ErrorCode property is the most boring one, as it always returns NativeErrorCode.
.NET Framework, Mono 6.8.0.105:

public override int ErrorCode {
    //
    // the base class returns the HResult with this property
    // we need the Win32 Error Code, hence the override.
    //
    get {
        return NativeErrorCode;
    }
}

In .NET Core 3.1.3:

public override int ErrorCode => base.NativeErrorCode;

Writing cross-platform socket error handling

Circling back to the original method we started this post with, we rewrote ShouldRetryConnection as follows:

protected virtual bool ShouldRetryConnection(Exception ex)
{
    if (ex is SocketException sx)
        return sx.SocketErrorCode == SocketError.ConnectionRefused;
    return false;
}

There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.

Overview of the native error codes

In some situations, you may want to have a table with native error codes on different operating systems. We can get these values with the following code snippet:

var allErrors = Enum.GetValues(typeof(SocketError)).Cast<SocketError>().ToList();
var maxNameWidth = allErrors.Select(x => x.ToString().Length).Max();
foreach (var socketError in allErrors)
{
    var name = socketError.ToString().PadRight(maxNameWidth);
    var code = new SocketException((int) socketError).NativeErrorCode.ToString().PadLeft(7);
    Console.WriteLine($TEXT$quot;| {name} | {code} |");
}

We executed this program on Windows, Linux, and macOS. Here are the aggregated results:

SocketError Windows Linux macOS
Success 0 0 0
OperationAborted 995 125 89
IOPending 997 115 36
Interrupted 10004 4 4
AccessDenied 10013 13 13
Fault 10014 14 14
InvalidArgument 10022 22 22
TooManyOpenSockets 10024 23 23
WouldBlock 10035 11 35
InProgress 10036 115 36
AlreadyInProgress 10037 114 37
NotSocket 10038 88 38
DestinationAddressRequired 10039 89 39
MessageSize 10040 90 40
ProtocolType 10041 91 41
ProtocolOption 10042 92 42
ProtocolNotSupported 10043 93 43
SocketNotSupported 10044 94 44
OperationNotSupported 10045 95 45
ProtocolFamilyNotSupported 10046 96 46
AddressFamilyNotSupported 10047 97 47
AddressAlreadyInUse 10048 98 48
AddressNotAvailable 10049 99 49
NetworkDown 10050 100 50
NetworkUnreachable 10051 101 51
NetworkReset 10052 102 52
ConnectionAborted 10053 103 53
ConnectionReset 10054 104 54
NoBufferSpaceAvailable 10055 105 55
IsConnected 10056 106 56
NotConnected 10057 107 57
Shutdown 10058 32 32
TimedOut 10060 110 60
ConnectionRefused 10061 111 61
HostDown 10064 112 64
HostUnreachable 10065 113 65
ProcessLimit 10067 10067 10067
SystemNotReady 10091 10091 10091
VersionNotSupported 10092 10092 10092
NotInitialized 10093 10093 10093
Disconnecting 10101 108 58
TypeNotFound 10109 10109 10109
HostNotFound 11001 -131073 -131073
TryAgain 11002 11 35
NoRecovery 11003 11003 11003
NoData 11004 61 96
SocketError -1 -1 -1

This table may be useful if you work with native socket error codes.

Summary

From this investigation, we’ve learned the following:

  • SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements always correspond to the Windows socket error codes.
  • SocketException.ErrorCode always returns SocketException.NativeErrorCode.
  • SocketException.NativeErrorCode on .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core, SocketException.NativeErrorCode equals the corresponding native error code from the current operating system.

SocketErrors-Blog
A few practical recommendations:

  • If you want to write portable code, always use SocketException.SocketErrorCode and compare it with the values of SocketError. Never use raw numerical error codes.
  • If you want to get the native error code on .NET Core (e.g., for passing to another native program), use SocketException.NativeErrorCode. Remember that different Unix-based operating systems (e.g., Linux, macOS, Solaris) have different native code sets. You can get the exact values of the native error codes by using the errno command.

References

  • Microsoft Docs: Windows Sockets Error Codes
  • IBM Knowledge Center: TCP/IP error codes
  • MariaDB: Operating System Error Codes
  • gnu.org: Error Codes
  • Stackoverflow: Identical Error Codes

Subscribe to Blog updates

Discover more

This blog post was originally posted on JetBrains .NET blog.

Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:

protected virtual bool ShouldRetryConnection (Exception ex, int attemptNumber)
{
    var sx = ex as SocketException;
    if (sx != null) {
        if (sx.ErrorCode == 10061) //connection refused
            return true;
    }
    return false;
}

In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException documentation, we will learn that this class has three different properties with error codes:

  • SocketError SocketErrorCode: Gets the error code that is associated with this exception.
  • int ErrorCode: Gets the error code that is associated with this exception.
  • int NativeErrorCode: Gets the Win32 error code associated with this exception.

What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection on .NET Core? Let’s figure it all out!

Digging into the problem

Let’s start with the following program, which prints error code property values for SocketError.ConnectionRefused:

var se = new SocketException((int) SocketError.ConnectionRefused);
Console.WriteLine((int)se.SocketErrorCode);
Console.WriteLine(se.ErrorCode);
Console.WriteLine(se.NativeErrorCode);

If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:

SocketErrorCode ErrorCode NativeErrorCode
.NET Framework 10061 10061 10061
Mono 10061 10061 10061
.NET Core 10061 10061 10061

10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED).
Now let’s run the same program on Linux:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 111 111

As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode and NativeErrorCode (111).
Finally, let’s check macOS:

SocketErrorCode ErrorCode NativeErrorCode
Mono 10061 10061 10061
.NET Core 10061 61 61

Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode and NativeErrorCode.
In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED):

  • AIX: 79
  • HP-UX: 239
  • Solaris: 146

For a better understanding of what’s going on, let’s check out the source code of all the properties.

SocketErrorCode

SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements are the same on all the runtimes (see its implementation in .NET Framework, .NET Core 3.1.3, and Mono 6.8.0.105):

public enum SocketError
{
    SocketError = -1, // 0xFFFFFFFF
    Success = 0,
    OperationAborted = 995, // 0x000003E3
    IOPending = 997, // 0x000003E5
    Interrupted = 10004, // 0x00002714
    AccessDenied = 10013, // 0x0000271D
    Fault = 10014, // 0x0000271E
    InvalidArgument = 10022, // 0x00002726
    TooManyOpenSockets = 10024, // 0x00002728
    WouldBlock = 10035, // 0x00002733
    InProgress = 10036, // 0x00002734
    AlreadyInProgress = 10037, // 0x00002735
    NotSocket = 10038, // 0x00002736
    DestinationAddressRequired = 10039, // 0x00002737
    MessageSize = 10040, // 0x00002738
    ProtocolType = 10041, // 0x00002739
    ProtocolOption = 10042, // 0x0000273A
    ProtocolNotSupported = 10043, // 0x0000273B
    SocketNotSupported = 10044, // 0x0000273C
    OperationNotSupported = 10045, // 0x0000273D
    ProtocolFamilyNotSupported = 10046, // 0x0000273E
    AddressFamilyNotSupported = 10047, // 0x0000273F
    AddressAlreadyInUse = 10048, // 0x00002740
    AddressNotAvailable = 10049, // 0x00002741
    NetworkDown = 10050, // 0x00002742
    NetworkUnreachable = 10051, // 0x00002743
    NetworkReset = 10052, // 0x00002744
    ConnectionAborted = 10053, // 0x00002745
    ConnectionReset = 10054, // 0x00002746
    NoBufferSpaceAvailable = 10055, // 0x00002747
    IsConnected = 10056, // 0x00002748
    NotConnected = 10057, // 0x00002749
    Shutdown = 10058, // 0x0000274A
    TimedOut = 10060, // 0x0000274C
    ConnectionRefused = 10061, // 0x0000274D
    HostDown = 10064, // 0x00002750
    HostUnreachable = 10065, // 0x00002751
    ProcessLimit = 10067, // 0x00002753
    SystemNotReady = 10091, // 0x0000276B
    VersionNotSupported = 10092, // 0x0000276C
    NotInitialized = 10093, // 0x0000276D
    Disconnecting = 10101, // 0x00002775
    TypeNotFound = 10109, // 0x0000277D
    HostNotFound = 11001, // 0x00002AF9
    TryAgain = 11002, // 0x00002AFA
    NoRecovery = 11003, // 0x00002AFB
    NoData = 11004, // 0x00002AFC
}

These values correspond to the Windows Sockets Error Codes.

NativeErrorCode

In .NET Framework and Mono, SocketErrorCode and NativeErrorCode always have the same values:

public SocketError SocketErrorCode {
    //
    // the base class returns the HResult with this property
    // we need the Win32 Error Code, hence the override.
    //
    get {
        return (SocketError)NativeErrorCode;
    }
}

In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):

public SocketException(int errorCode) : this((SocketError)errorCode)
// ...
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))

The Windows implementation of GetNativeErrorForSocketError is trivial (see SocketException.Windows.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    // SocketError values map directly to Win32 error codes
    return (int)error;
}

The Unix implementation is more complicated (see SocketException.Unix.cs):

private static int GetNativeErrorForSocketError(SocketError error)
{
    int nativeErr = (int)error;
    if (error != SocketError.SocketError)
    {
        Interop.Error interopErr;

        // If an interop error was not found, then don't invoke Info().RawErrno as that will fail with assert.
        if (SocketErrorPal.TryGetNativeErrorForSocketError(error, out interopErr))
        {
            nativeErr = interopErr.Info().RawErrno;
        }
    }

    return nativeErr;
}

TryGetNativeErrorForSocketError should convert SocketError to the native Unix error code.
Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):

private const int NativeErrorToSocketErrorCount = 42;
private const int SocketErrorToNativeErrorCount = 40;

// No Interop.Errors are included for the following SocketErrors, as there's no good mapping:
// - SocketError.NoRecovery
// - SocketError.NotInitialized
// - SocketError.ProcessLimit
// - SocketError.SocketError
// - SocketError.SystemNotReady
// - SocketError.TypeNotFound
// - SocketError.VersionNotSupported

private static readonly Dictionary&lt;Interop.Error, SocketError&gt; s_nativeErrorToSocketError = new Dictionary&lt;Interop.Error, SocketError&gt;(NativeErrorToSocketErrorCount)
{
    { Interop.Error.EACCES, SocketError.AccessDenied },
    { Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse },
    { Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable },
    { Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported },
    { Interop.Error.EAGAIN, SocketError.WouldBlock },
    { Interop.Error.EALREADY, SocketError.AlreadyInProgress },
    { Interop.Error.EBADF, SocketError.OperationAborted },
    { Interop.Error.ECANCELED, SocketError.OperationAborted },
    { Interop.Error.ECONNABORTED, SocketError.ConnectionAborted },
    { Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused },
    { Interop.Error.ECONNRESET, SocketError.ConnectionReset },
    { Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired },
    { Interop.Error.EFAULT, SocketError.Fault },
    { Interop.Error.EHOSTDOWN, SocketError.HostDown },
    { Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available
    { Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable },
    { Interop.Error.EINPROGRESS, SocketError.InProgress },
    { Interop.Error.EINTR, SocketError.Interrupted },
    { Interop.Error.EINVAL, SocketError.InvalidArgument },
    { Interop.Error.EISCONN, SocketError.IsConnected },
    { Interop.Error.EMFILE, SocketError.TooManyOpenSockets },
    { Interop.Error.EMSGSIZE, SocketError.MessageSize },
    { Interop.Error.ENETDOWN, SocketError.NetworkDown },
    { Interop.Error.ENETRESET, SocketError.NetworkReset },
    { Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable },
    { Interop.Error.ENFILE, SocketError.TooManyOpenSockets },
    { Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable },
    { Interop.Error.ENODATA, SocketError.NoData },
    { Interop.Error.ENOENT, SocketError.AddressNotAvailable },
    { Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption },
    { Interop.Error.ENOTCONN, SocketError.NotConnected },
    { Interop.Error.ENOTSOCK, SocketError.NotSocket },
    { Interop.Error.ENOTSUP, SocketError.OperationNotSupported },
    { Interop.Error.EPERM, SocketError.AccessDenied },
    { Interop.Error.EPIPE, SocketError.Shutdown },
    { Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported },
    { Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported },
    { Interop.Error.EPROTOTYPE, SocketError.ProtocolType },
    { Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported },
    { Interop.Error.ESHUTDOWN, SocketError.Disconnecting },
    { Interop.Error.SUCCESS, SocketError.Success },
    { Interop.Error.ETIMEDOUT, SocketError.TimedOut },
};

private static readonly Dictionary&lt;SocketError, Interop.Error&gt; s_socketErrorToNativeError = new Dictionary&lt;SocketError, Interop.Error&gt;(SocketErrorToNativeErrorCount)
{
    // This is *mostly* an inverse mapping of s_nativeErrorToSocketError.  However, some options have multiple mappings and thus
    // can't be inverted directly.  Other options don't have a mapping from native to SocketError, but when presented with a SocketError,
    // we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but
    // SocketError.IOPending also maps closest to EINPROGRESS.  As such, roundtripping won't necessarily provide the original value 100% of the time,
    // but it's the best we can do given the mismatch between Interop.Error and SocketError.

    { SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM
    { SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE  },
    { SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL },
    { SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT  },
    { SocketError.AlreadyInProgress, Interop.Error.EALREADY },
    { SocketError.ConnectionAborted, Interop.Error.ECONNABORTED },
    { SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED },
    { SocketError.ConnectionReset, Interop.Error.ECONNRESET },
    { SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ },
    { SocketError.Disconnecting, Interop.Error.ESHUTDOWN },
    { SocketError.Fault, Interop.Error.EFAULT },
    { SocketError.HostDown, Interop.Error.EHOSTDOWN },
    { SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND },
    { SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH },
    { SocketError.InProgress, Interop.Error.EINPROGRESS },
    { SocketError.Interrupted, Interop.Error.EINTR },
    { SocketError.InvalidArgument, Interop.Error.EINVAL },
    { SocketError.IOPending, Interop.Error.EINPROGRESS },
    { SocketError.IsConnected, Interop.Error.EISCONN },
    { SocketError.MessageSize, Interop.Error.EMSGSIZE },
    { SocketError.NetworkDown, Interop.Error.ENETDOWN },
    { SocketError.NetworkReset, Interop.Error.ENETRESET },
    { SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH },
    { SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS },
    { SocketError.NoData, Interop.Error.ENODATA },
    { SocketError.NotConnected, Interop.Error.ENOTCONN },
    { SocketError.NotSocket, Interop.Error.ENOTSOCK },
    { SocketError.OperationAborted, Interop.Error.ECANCELED },
    { SocketError.OperationNotSupported, Interop.Error.ENOTSUP },
    { SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT },
    { SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT },
    { SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT },
    { SocketError.ProtocolType, Interop.Error.EPROTOTYPE },
    { SocketError.Shutdown, Interop.Error.EPIPE },
    { SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT },
    { SocketError.Success, Interop.Error.SUCCESS },
    { SocketError.TimedOut, Interop.Error.ETIMEDOUT },
    { SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE
    { SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing
    { SocketError.WouldBlock, Interop.Error.EAGAIN  },
};

internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno)
{
    return s_socketErrorToNativeError.TryGetValue(error, out errno);
}

Once we have an instance of Interop.Error, we call interopErr.Info().RawErrno. The implementation of RawErrno can be found in Interop.Errors.cs:

internal int RawErrno
{
    get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
}

[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")]
internal static extern int ConvertErrorPalToPlatform(Error error);

Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:

$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 No such device or address
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EAGAIN 11 Resource temporarily unavailable
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Device or resource busy
EEXIST 17 File exists
EXDEV 18 Invalid cross-device link
ENODEV 19 No such device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Numerical result out of range
EDEADLK 35 Resource deadlock avoided
ENAMETOOLONG 36 File name too long
ENOLCK 37 No locks available
ENOSYS 38 Function not implemented
ENOTEMPTY 39 Directory not empty
ELOOP 40 Too many levels of symbolic links
EWOULDBLOCK 11 Resource temporarily unavailable
ENOMSG 42 No message of desired type
EIDRM 43 Identifier removed
ECHRNG 44 Channel number out of range
EL2NSYNC 45 Level 2 not synchronized
EL3HLT 46 Level 3 halted
EL3RST 47 Level 3 reset
ELNRNG 48 Link number out of range
EUNATCH 49 Protocol driver not attached
ENOCSI 50 No CSI structure available
EL2HLT 51 Level 2 halted
EBADE 52 Invalid exchange
EBADR 53 Invalid request descriptor
EXFULL 54 Exchange full
ENOANO 55 No anode
EBADRQC 56 Invalid request code
EBADSLT 57 Invalid slot
EDEADLOCK 35 Resource deadlock avoided
EBFONT 59 Bad font file format
ENOSTR 60 Device not a stream
ENODATA 61 No data available
ETIME 62 Timer expired
ENOSR 63 Out of streams resources
ENONET 64 Machine is not on the network
ENOPKG 65 Package not installed
EREMOTE 66 Object is remote
ENOLINK 67 Link has been severed
EADV 68 Advertise error
ESRMNT 69 Srmount error
ECOMM 70 Communication error on send
EPROTO 71 Protocol error
EMULTIHOP 72 Multihop attempted
EDOTDOT 73 RFS specific error
EBADMSG 74 Bad message
EOVERFLOW 75 Value too large for defined data type
ENOTUNIQ 76 Name not unique on network
EBADFD 77 File descriptor in bad state
EREMCHG 78 Remote address changed
ELIBACC 79 Can not access a needed shared library
ELIBBAD 80 Accessing a corrupted shared library
ELIBSCN 81 .lib section in a.out corrupted
ELIBMAX 82 Attempting to link in too many shared libraries
ELIBEXEC 83 Cannot exec a shared library directly
EILSEQ 84 Invalid or incomplete multibyte or wide character
ERESTART 85 Interrupted system call should be restarted
ESTRPIPE 86 Streams pipe error
EUSERS 87 Too many users
ENOTSOCK 88 Socket operation on non-socket
EDESTADDRREQ 89 Destination address required
EMSGSIZE 90 Message too long
EPROTOTYPE 91 Protocol wrong type for socket
ENOPROTOOPT 92 Protocol not available
EPROTONOSUPPORT 93 Protocol not supported
ESOCKTNOSUPPORT 94 Socket type not supported
EOPNOTSUPP 95 Operation not supported
EPFNOSUPPORT 96 Protocol family not supported
EAFNOSUPPORT 97 Address family not supported by protocol
EADDRINUSE 98 Address already in use
EADDRNOTAVAIL 99 Cannot assign requested address
ENETDOWN 100 Network is down
ENETUNREACH 101 Network is unreachable
ENETRESET 102 Network dropped connection on reset
ECONNABORTED 103 Software caused connection abort
ECONNRESET 104 Connection reset by peer
ENOBUFS 105 No buffer space available
EISCONN 106 Transport endpoint is already connected
ENOTCONN 107 Transport endpoint is not connected
ESHUTDOWN 108 Cannot send after transport endpoint shutdown
ETOOMANYREFS 109 Too many references: cannot splice
ETIMEDOUT 110 Connection timed out
ECONNREFUSED 111 Connection refused
EHOSTDOWN 112 Host is down
EHOSTUNREACH 113 No route to host
EALREADY 114 Operation already in progress
EINPROGRESS 115 Operation now in progress
ESTALE 116 Stale file handle
EUCLEAN 117 Structure needs cleaning
ENOTNAM 118 Not a XENIX named type file
ENAVAIL 119 No XENIX semaphores available
EISNAM 120 Is a named type file
EREMOTEIO 121 Remote I/O error
EDQUOT 122 Disk quota exceeded
ENOMEDIUM 123 No medium found
EMEDIUMTYPE 124 Wrong medium type
ECANCELED 125 Operation canceled
ENOKEY 126 Required key not available
EKEYEXPIRED 127 Key has expired
EKEYREVOKED 128 Key has been revoked
EKEYREJECTED 129 Key was rejected by service
EOWNERDEAD 130 Owner died
ENOTRECOVERABLE 131 State not recoverable
ERFKILL 132 Operation not possible due to RF-kill
EHWPOISON 133 Memory page has hardware error
ENOTSUP 95 Operation not supported

Note that errno may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils to get this utility.
Here is a typical output on macOS:

$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 Device not configured
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EDEADLK 11 Resource deadlock avoided
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Resource busy
EEXIST 17 File exists
EXDEV 18 Cross-device link
ENODEV 19 Operation not supported by device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Result too large
EAGAIN 35 Resource temporarily unavailable
EWOULDBLOCK 35 Resource temporarily unavailable
EINPROGRESS 36 Operation now in progress
EALREADY 37 Operation already in progress
ENOTSOCK 38 Socket operation on non-socket
EDESTADDRREQ 39 Destination address required
EMSGSIZE 40 Message too long
EPROTOTYPE 41 Protocol wrong type for socket
ENOPROTOOPT 42 Protocol not available
EPROTONOSUPPORT 43 Protocol not supported
ESOCKTNOSUPPORT 44 Socket type not supported
ENOTSUP 45 Operation not supported
EPFNOSUPPORT 46 Protocol family not supported
EAFNOSUPPORT 47 Address family not supported by protocol family
EADDRINUSE 48 Address already in use
EADDRNOTAVAIL 49 Can`t assign requested address
ENETDOWN 50 Network is down
ENETUNREACH 51 Network is unreachable
ENETRESET 52 Network dropped connection on reset
ECONNABORTED 53 Software caused connection abort
ECONNRESET 54 Connection reset by peer
ENOBUFS 55 No buffer space available
EISCONN 56 Socket is already connected
ENOTCONN 57 Socket is not connected
ESHUTDOWN 58 Can`t send after socket shutdown
ETOOMANYREFS 59 Too many references: can`t splice
ETIMEDOUT 60 Operation timed out
ECONNREFUSED 61 Connection refused
ELOOP 62 Too many levels of symbolic links
ENAMETOOLONG 63 File name too long
EHOSTDOWN 64 Host is down
EHOSTUNREACH 65 No route to host
ENOTEMPTY 66 Directory not empty
EPROCLIM 67 Too many processes
EUSERS 68 Too many users
EDQUOT 69 Disc quota exceeded
ESTALE 70 Stale NFS file handle
EREMOTE 71 Too many levels of remote in path
EBADRPC 72 RPC struct is bad
ERPCMISMATCH 73 RPC version wrong
EPROGUNAVAIL 74 RPC prog. not avail
EPROGMISMATCH 75 Program version wrong
EPROCUNAVAIL 76 Bad procedure for program
ENOLCK 77 No locks available
ENOSYS 78 Function not implemented
EFTYPE 79 Inappropriate file type or format
EAUTH 80 Authentication error
ENEEDAUTH 81 Need authenticator
EPWROFF 82 Device power is off
EDEVERR 83 Device error
EOVERFLOW 84 Value too large to be stored in data type
EBADEXEC 85 Bad executable (or shared library)
EBADARCH 86 Bad CPU type in executable
ESHLIBVERS 87 Shared library version mismatch
EBADMACHO 88 Malformed Mach-o file
ECANCELED 89 Operation canceled
EIDRM 90 Identifier removed
ENOMSG 91 No message of desired type
EILSEQ 92 Illegal byte sequence
ENOATTR 93 Attribute not found
EBADMSG 94 Bad message
EMULTIHOP 95 EMULTIHOP (Reserved)
ENODATA 96 No message available on STREAM
ENOLINK 97 ENOLINK (Reserved)
ENOSR 98 No STREAM resources
ENOSTR 99 Not a STREAM
EPROTO 100 Protocol error
ETIME 101 STREAM ioctl timeout
EOPNOTSUPP 102 Operation not supported on socket
ENOPOLICY 103 Policy not found
ENOTRECOVERABLE 104 State not recoverable
EOWNERDEAD 105 Previous owner died
EQFULL 106 Interface output queue is full
ELAST 106 Interface output queue is full

Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException from!

ErrorCode

The ErrorCode property is the most boring one, as it always returns NativeErrorCode.
.NET Framework, Mono 6.8.0.105:

public override int ErrorCode {
    //
    // the base class returns the HResult with this property
    // we need the Win32 Error Code, hence the override.
    //
    get {
        return NativeErrorCode;
    }
}

In .NET Core 3.1.3:

public override int ErrorCode =&gt; base.NativeErrorCode;

Writing cross-platform socket error handling

Circling back to the original method we started this post with, we rewrote ShouldRetryConnection as follows:

protected virtual bool ShouldRetryConnection(Exception ex)
{
    if (ex is SocketException sx)
        return sx.SocketErrorCode == SocketError.ConnectionRefused;
    return false;
}

There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.

Overview of the native error codes

In some situations, you may want to have a table with native error codes on different operating systems. We can get these values with the following code snippet:

var allErrors = Enum.GetValues(typeof(SocketError)).Cast&lt;SocketError&gt;().ToList();
var maxNameWidth = allErrors.Select(x =&gt; x.ToString().Length).Max();
foreach (var socketError in allErrors)
{
    var name = socketError.ToString().PadRight(maxNameWidth);
    var code = new SocketException((int) socketError).NativeErrorCode.ToString().PadLeft(7);
    Console.WriteLine("| {name} | {code} |");
}

We executed this program on Windows, Linux, and macOS. Here are the aggregated results:

SocketError Windows Linux macOS
Success 0 0 0
OperationAborted 995 125 89
IOPending 997 115 36
Interrupted 10004 4 4
AccessDenied 10013 13 13
Fault 10014 14 14
InvalidArgument 10022 22 22
TooManyOpenSockets 10024 23 23
WouldBlock 10035 11 35
InProgress 10036 115 36
AlreadyInProgress 10037 114 37
NotSocket 10038 88 38
DestinationAddressRequired 10039 89 39
MessageSize 10040 90 40
ProtocolType 10041 91 41
ProtocolOption 10042 92 42
ProtocolNotSupported 10043 93 43
SocketNotSupported 10044 94 44
OperationNotSupported 10045 95 45
ProtocolFamilyNotSupported 10046 96 46
AddressFamilyNotSupported 10047 97 47
AddressAlreadyInUse 10048 98 48
AddressNotAvailable 10049 99 49
NetworkDown 10050 100 50
NetworkUnreachable 10051 101 51
NetworkReset 10052 102 52
ConnectionAborted 10053 103 53
ConnectionReset 10054 104 54
NoBufferSpaceAvailable 10055 105 55
IsConnected 10056 106 56
NotConnected 10057 107 57
Shutdown 10058 32 32
TimedOut 10060 110 60
ConnectionRefused 10061 111 61
HostDown 10064 112 64
HostUnreachable 10065 113 65
ProcessLimit 10067 10067 10067
SystemNotReady 10091 10091 10091
VersionNotSupported 10092 10092 10092
NotInitialized 10093 10093 10093
Disconnecting 10101 108 58
TypeNotFound 10109 10109 10109
HostNotFound 11001 -131073 -131073
TryAgain 11002 11 35
NoRecovery 11003 11003 11003
NoData 11004 61 96
SocketError -1 -1 -1

This table may be useful if you work with native socket error codes.

Summary

From this investigation, we’ve learned the following:

  • SocketException.SocketErrorCode returns a value from the SocketError enum. The numerical values of the enum elements always correspond to the Windows socket error codes.
  • SocketException.ErrorCode always returns SocketException.NativeErrorCode.
  • SocketException.NativeErrorCode on .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core, SocketException.NativeErrorCode equals the corresponding native error code from the current operating system.

A few practical recommendations:

  • If you want to write portable code, always use SocketException.SocketErrorCode and compare it with the values of SocketError. Never use raw numerical error codes.
  • If you want to get the native error code on .NET Core (e.g., for passing to another native program), use SocketException.NativeErrorCode. Remember that different Unix-based operating systems (e.g., Linux, macOS, Solaris) have different native code sets. You can get the exact values of the native error codes by using the errno command.

References

  • Microsoft Docs: Windows Sockets Error Codes
  • IBM Knowledge Center: TCP/IP error codes
  • MariaDB: Operating System Error Codes
  • gnu.org: Error Codes
  • Stackoverflow: Identical Error Codes

Ошибки сокетов

Модуль socket был написан для обеспечения удобного интерфейса к сокетам BSD.
Были приняты необходимые меры для того, чтобы эти функции работали одинаково хорошо в
реализации как для Win32, так и Unix. Почти все функции, при определённых условиях,
могут завершиться с ошибкой и вызовут ошибку уровня
E_WARNING. Иногда, разработчики препятствуют этому.
Например, функция socket_read() может внезапно вызвать
ошибку уровня E_WARNING, потому что соединение неожиданно оборвалось.
Обычная практика подавлять предупреждение при помощи оператора
@ и перехватывать код ошибки в приложении при помощи функции
socket_last_error(). Вы можете вызывать функцию
socket_strerror() с кодом ошибки для получения строки, описывающей
ошибку. Смотрите описание этих функций для более подробной информации.

Замечание:

Сообщения E_WARNING, вызываемые модулем socket,
будут на английском языке, а полученное сообщение об ошибке будет появляться в
зависимости от настроек текущей локали (LC_MESSAGES):

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

There are no user contributed notes for this page.

  • Коды ошибок skoda rapid
  • Коды ошибок skoda fabia
  • Коды ошибок ski doo
  • Коды ошибок sinumerik 808d
  • Коды ошибок sinamics v20