Recommended Answers
I can’t see how you’re calling these functions and what values the variables have. Post more code that demonstrates how you use these functions and I’ll have a look at it.
Jump to Post
You have threads, and a single unguarded global variable.
You have two functions with very similar names,
— sockConnect
— connectSockYour ‘state’ global variable has two flags which seem to mean the same thing.
— bool ic;
— bool inuse;Can you do what you want …
Jump to Post
Well those kinds of problems won’t go away by magic just by using threads.
Start with a simple client/server as two separate processes, talking via 127.0.0.1
http://beej.us/guide/bgnet/output/html/multipage/clientserver.htmlThen add the randomness to your send, again without using threads.
Jump to Post
All 9 Replies
Nick Evan
4,005
Industrious Poster
Team Colleague
Featured Poster
13 Years Ago
I can’t see how you’re calling these functions and what values the variables have. Post more code that demonstrates how you use these functions and I’ll have a look at it.
13 Years Ago
void setPort(String ^port){
connectSock();
P.port=To_string(port);
args.param="";
_beginthread(sendHTTP,0,&args);
args.param="newmap=1";
_beginthread(sendHTTP,0,&args);
}
13 Years Ago
since nobody seems to be able to help me can someone give me an example of what im trying to do?
(beej doesnt help)
or point me somewhere they can help me?
Salem
5,138
Posting Sage
13 Years Ago
You have threads, and a single unguarded global variable.
You have two functions with very similar names,
— sockConnect
— connectSock
Your ‘state’ global variable has two flags which seem to mean the same thing.
— bool ic;
— bool inuse;
Can you do what you want (once) as a single thread?
Because at the moment, it’s a confused mess of half-cooked ideas all milling around as a bunch of race conditions.
13 Years Ago
i need to send traffic at random times. the packets are gathered as the user interacts
if i create a new socket when i want to send i get an error saying the socket is in use, and im using threads to send data so if i set so_reuse it wont help.
if i use one socket it gets disconnected for some reason, and when the program closes i get a fin flood.
so how do i do this????
Salem
5,138
Posting Sage
13 Years Ago
13 Years Ago
so i rewrote it without the threads, but i still get the rst issue i first got
i send 2 packets and on the 3rd it replies with rst… any thoughts on why?
Salem
5,138
Posting Sage
13 Years Ago
Not without seeing more code — no.
13 Years Ago
there is no more code- than what ive posted
void connectSock(){
psock.sockVer = MAKEWORD(1, 1);
psock.ic=false;
WSAStartup(psock.sockVer, &psock.wsaData);
char url[512];
sprintf(url, P.httpUrl.c_str());
memset(&psock.hints, 0, sizeof psock.hints);
psock.hints.ai_family = AF_UNSPEC;
psock.hints.ai_socktype = SOCK_STREAM;
getaddrinfo(url, "80", &psock.hints, &psock.srvrData);
psock.sock = socket(psock.srvrData->ai_family, psock.srvrData->ai_socktype, psock.srvrData->ai_protocol);
if (psock.sock == INVALID_SOCKET) {
closeSock(psock.sock);
P.Event="Socket fail... ";
std::stringstream outo;
outo << WSAGetLastError();
P.Event+=outo.str();
return ;
}
if(connect(psock.sock, psock.srvrData->ai_addr, psock.srvrData->ai_addrlen)<0){
P.Event="Connect Fail";
return ;
}
psock.ic=true;
}
void sendHTTP(string tpost){
if(!psock.ic)return;
try{
if(tpost.length()!=0)tpost+="&";
if(P.post.length()!=0)tpost+=P.post;
if(tpost.length()!=0)tpost+="&";
tpost+="port="+P.port;
string buffer2="POST "+P.path+" HTTP/1.0rnHost: "+P.httpUrl+"rnUser-Agent: Mozilla/4.0rnContent-Length: ";
std::stringstream outo;
outo << tpost.length();
buffer2+= outo.str();
buffer2+="rnContent-Type: application/x-www-form-urlencodedrnrn";
buffer2+=tpost;
buffer2+="n";
if(send(psock.sock, buffer2.c_str(), buffer2.length(), 0)<buffer2.length()){
P.Event="Send error ";
string s=(string)strerror(errno);
P.Event+=(s);
std::stringstream outo;
outo << WSAGetLastError();
P.Event+=outo.str();
sendHTTP( tpost);
return;
}
}catch(Exception ^ex){
}
return;
}
void setPort(String ^port){
connectSock();
P.port=To_string(port);
sendHTTP("");
sendHTTP("newmap=1");
}
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
При работе с сокетами бывают исключительные ситуации, при которых возникают ошибки с некими кодами. Немножко поискав — нашел описание ошибок. Решил привести данное описание в своем блоге:
Socket error 10004 — Interrupted function call
Socket error 10013 — Permission denied
Socket error 10014 — Bad address
Socket error 10022 — Invalid argument
Socket error 10024 — Too many open files
Socket error 10035 — Resource temporarily unavailable
Socket error 10036 — Operation now in progress
Socket error 10037 — Operation already in progress
Socket error 10038 — Socket operation on non-socket
Socket error 10039 — Destination address required
Socket error 10040 — Message too long
Socket error 10041 — Protocol wrong type for socket
Socket error 10042 — Bad protocol option
Socket error 10043 — Protocol not supported
Socket error 10044 — Socket type not supported
Socket error 10045 — Operation not supported
Socket error 10046 — Protocol family not supported
Socket error 10047 — Address family not supported by protocol family
Socket error 10048 — Address already in use
Socket error 10049 — Cannot assign requested address
Socket error 10050 — Network is down
Socket error 10051 — Network is unreachable
Socket error 10052 — Network dropped connection on reset
Socket error 10053 — Software caused connection abort
Socket error 10054 — Connection reset by peer
Socket error 10055 — No buffer space available
Socket error 10056 — Socket is already connected
Socket error 10057 — Socket is not connected
Socket error 10058 — Cannot send after socket shutdown
Socket error 10060 — Connection timed out
Socket error 10061 — Connection refused
Socket error 10064 — Host is down
Socket error 10065 — No route to host
Socket error 10067 — Too many processes
Socket error 10091 — Network subsystem is unavailable
Socket error 10092 — WINSOCK.DLL version out of range
Socket error 10093 — Successful WSAStartup not yet performed
Socket error 10094 — Graceful shutdown in progress
Socket error 11001 — Host not found
Socket error 11002 — Non-authoritative host not found
Socket error 11003 — This is a non-recoverable error
Socket error 11004 — Valid name, no data record of requested type
-
Question
-
Hi,
I am using the CAyncSocket and CSocket to transfer data between server and client sides. I got the error like :
Debug Assertion Failed !
f:ddvctoolsvc7libsshipatlmfcsrcmfcsockcore.cpp line: 947
How can I resolve it?
Thanks.
All replies
-
A little info about what you are doing with the socket would help. Look in the debugger stack window to find out which of your calls led to the assertion.
Did you call a socket function from a thread that did not create the socket?
-
It is not the thread issue, I think. It looks like the synchronization between server and client. The problem happens at the Receive(buff, 4096)) line at client side.
TCHAR buff[4096];
int nRead = 4096;
if ((nRead = m_pClientSock->Receive(buff, 4096)) == SOCKET_ERROR)
{
}
Sometimes, Receive() line can receive the feedback information from server side. But sometimes, it brings the error mentioned in my post. It does not always happen. Also, when I set the breakpoint and this line is hit, it did not assign a value
to the nRead, and it popuped the error window immediately.Any ideas ? Thanks.
-
The assertion indicates that the socket does not exist, or exists in a different thread. Did the socket Create call return success? Maybe the socket has been closed? Destroyed? Or m_pClientSock is not pointing at the socket?
-
More information. If Receive() line runs before the server sends data back to client, it will cause the error. If Receive()
line runs after the server sends data back to client, it works. Any ideas about how the client side knows the server sends data back?I put the try … catch block for Receive()
line to catch the error exception, but the error cannot be caught, and the error window is immediately popups.
How to do exception handling here?Thanks.
-
Now I just put the 5 seconds waiting, Sleep(5000), before the Receive() line, and no error happens. But
it will worse the performance. Thanks. -
To know when the server sends data back the client side creates a message-only window (m_hSocketWindow in the ASSERT) to receive a Windows message posted by winsock. The assertion failure shows that you do not have that message-only window. The window
should be created in sockcore.cpp line 476. You could check that, and then check all the places m_hSocketWindow is modified to try and find out why you don’t have the message-only window.An assertion is not an exception and cannot be caught. An assertion is a debug tool to let the programmer know that assumed and required preconditions do not exist. It means the programmer has made a mistake, not the machine or the environment.
-
What is the message-only window? How to create such message-only
window to avoid the above error? Any examples or hyperlinks? Thanks. -
Also, after I use Sleep(5000), why will the
message-only window be found? Any relation between the Sleep(5000) and the
message-only window ? Thanks. -
The message-only window is created for you automatically by CSocket/CAsyncSocket. You don’t have to do anything except create the socket normally. The window is an implementation detail that is normally of no interest. But the assertion is telling
us that it does not exist, so it either was not created or it has been destroyed. (Or it was created in another thread.)There are working examples of CSocket/CAsyncSocket in MSDN, including MFCsocs here:
http://support.microsoft.com/kb/185728/e
You can probably find your problem by studying that sample code and comparing it to yours, by code inspection or by analyzing its operation with the debugger.
-
From Visual Studio debugger, I could not find any clue for it.
However, at the hyperlink of http://support.microsoft.com/kb/185728/e , I found out the following part:
When you use a CSocket Receive and Send outside OnReceive and OnSend (in other words, when you use a default do-nothing OnSend and OnReceive), it is okay
to use Receive and Send in a loop or use them with CArchive and CSocketFile.In fact, in my code, I am using CSocket Receive outside OnReceive. But I did not use the loop and CArchive/CSocketFile.
Is this the reason? Any hyperlink for example for just using CSocket Receive outside OnReceive?
Thanks. -
I would expect the window to be created before the Connect call returns, but I have not used this mode of calling outside of OnReceive and OnSend so can’t be sure. You should be able to check that with the debugger: Is the m_hSocketWindow created during
the Connect call?Does your call to Connect always return non-zero? Something else to try might be waiting until you get the OnConnect callback before doing any Send or Receive calls.
-
The following code is what I am using. Most of them is from the sample of http://support.microsoft.com/kb/185728/e
When this code runs, the line of if ( 0 == m_pClientSock->Connect(m_strServer, m_port) ) always return the code of 10056, which
menas «The socket is not connected». If the line Sleep(8000);
is there, it works. If this line is commented,it fails.
Perhaps, showing the code is helpful for finding the solution. Moreover, I did not see the information for
m_hSocketWindow in the visual studio debugger. Thanks.
if (m_boolClient) { if ( m_pClientSock) { if (m_pClientSock->Send((LPCTSTR)m_strSend, m_strSend.GetLength() +1) == SOCKET_ERROR) { wsprintf(m_szError, "Failed to send on client socket: %d", m_pClientSock->GetLastError()); m_pClientSock->Close(); delete m_pClientSock; m_pClientSock = NULL; AfxMessageBox (m_szError); return ""; } m_strSend = ""; ////UpdateData(FALSE); } else { if ((m_pClientSock = new CClntSock(this)) == NULL) { AfxMessageBox ("Failed to allocate client socket! Close and restart app."); return ""; } if (!m_pClientSock->Create()) { wsprintf(m_szError, "Failed to create client socket: %d! Close and restart app.", m_pClientSock->GetLastError()); AfxMessageBox (m_szError); return ""; } if (!m_pClientSock->Connect(m_strServer, m_port)) { wsprintf(m_szError, "Failed to connect to server: %d.", m_pClientSock->GetLastError()); AfxMessageBox (m_szError); m_pClientSock->Close(); delete m_pClientSock; m_pClientSock = NULL; return ""; } if (m_pClientSock->Send((LPCTSTR)m_strSend, m_strSend.GetLength() +1) == SOCKET_ERROR) { wsprintf(m_szError, "Failed to send on client socket: %d", m_pClientSock->GetLastError()); m_pClientSock->Close(); delete m_pClientSock; m_pClientSock = NULL; AfxMessageBox (m_szError); return ""; } m_strSend = ""; } } else { if ( m_pSrvrSock) { m_pSrvrSock->m_sendBuffer = m_strSend; m_pSrvrSock->m_nBytesSent = 0; m_pSrvrSock->m_nBytesBufferSize = m_strSend.GetLength() + 1; m_pSrvrSock->DoAsyncSendBuff(); m_strSend = ""; } else { AfxMessageBox ("Message socket not established yet"); } } //Sleep(8000); TCHAR buff[4096]; int nRead = 4096; try { if ( 0 == m_pClientSock->Connect(m_strServer, m_port) ) { int errorNumber = m_pClientSock->GetLastError(); if(errorNumber != 10056) // 10056 -- "The socket is not connected" { wsprintf(m_szError, "Failed to Connect: %d", errorNumber); m_pClientSock->Close(); delete m_pClientSock; m_pClientSock = NULL; AfxMessageBox (m_szError); return ""; } } if ((nRead = m_pClientSock->Receive(buff, 4096)) == SOCKET_ERROR) { wsprintf(m_szError, "Failed to receive on client socket: %d", m_pClientSock->GetLastError()); m_pClientSock->Close(); delete m_pClientSock; m_pClientSock = NULL; AfxMessageBox (m_szError); return ""; } } catch(CException* e) { string msg = "Microscope Control failed to send receive to server: "; AfxMessageBox(msg.c_str()); } //nRead = m_pClientSock->Receive(buff, 4096); //if (nRead != SOCKET_ERROR) { if (nRead) { buff[nRead] = 0; CString szTemp(buff); returnedStringFromServer = static_cast<LPCSTR>(CStringA(szTemp)); if (szTemp.CompareNoCase("bye") == 0 ) { m_pClientSock->ShutDown(); } } else { m_pClientSock->Close(); } } -
I have tried several times , but I haven’t got Assertion error. can you check your newwork?
-
Thanks for trying.
I just tried it on the sample code from http://support.microsoft.com/kb/185728/e . I added the receive part after sending on the client side. Also I added the send part immediately
after receiving on the server side. This modified sample version works.At client side, when the line of
«if ((nRead = m_pClientSock->Receive(buff, 4096)) == SOCKET_ERROR) » runs, it waits there
until themessage, which is sent from server, comes back to client side.
It looks like that the issue is the client code in our program. The client code in our program uses multiple
threads. It seems that Sleep(5000) can resolve this issue, but it will worse the performance. I am looking
for the different way to resolve it.
Also why can Sleep(5000)
resolve this issue in the multiple threads environment? It does not make sense for
me, either.
Any ideas about how to resolve the issue are very appreciated? Thanks a lot.
-
I saw this article, and I do not know how this article can help me.
Our client program is like this: two GUI dialogs are related with the socket. There is a main dialog when the program starts, and this main dialog call the class where the socket is located. After the the main dialog finishes, I will open another plug-in
dialog, and this dialog also uses the class mention above. If I do not put Sleep(5000) there, the line of «ASSERT(pState->m_hSocketWindow != NULL);» in the file of sockcore.cpp (947) will run. The error window will popup. If I put the Sleep(5000) there, the
line of «ASSERT(pState->m_hSocketWindow != NULL);» in the file of sockcore.cpp (947) will not run, at all. So no this error window popups.If you need more information, please let me know. Thanks.
-
Also, I am wondering if I can do something before the line of «if ((nRead = m_pClientSock->Receive(buff, 4096)) == SOCKET_ERROR)», so that this line just waits until the data comes back. But I do not know what I can do for it. Now I put the Sleep(5000)
there, which is not what I want. -
There could be problems with «after the main dialog finishes I will open another plug-in dialog, and this dialog also uses the class mentioned above.» When the main dialog finishes MFC starts destroying a lot of the program’s objects. It’s hard
to help without seeing the code. -
Thanks. How about the Sleep(5000) ? Any comments for it?
-
If no socket message is waiting when you call Receive then MFC loops around in a message pump while it waits. That’s when it hits the ASSERT that the message-only window does not exist.
-
Do you mean?
If the sever side has already sent the message back to client side before Receive line runs, it does not go to pump.
So ASSERT never hits and no error happens.If Receive line runs and waits there for the message back from the server side, it will loop around and hit the ASSERT.
So the error happens.This makes sense.
So I need to figure out why the message-only window disappear. Thanks.
-
I think Scott is correct.
If the receive loop cannot get any message after sending message successfully. That will cause a Assert error. -
Thanks guys for the helps. I researched the above problem.
On client side, the pState and pThread changed when I set a breakpoint at the line of 947 in the file of sockcore.cpp.
I attach two images, and there are differences in pState and pThread in them. It looks like the client side multiple threads causes this issue. The upper image is the status at the whole program opens, and the lower image is the status: after the whole program
opens, and then open the plugin.Could I know where I can get thus example for the client multiple threads using the CSocket/CAyncSoket? If thus example can base on the example code at http://support.microsoft.com/kb/185728/e ,
it will be great. In fact, I would like to know how to attach/deattach the socket on the multiple threads at the client side. -
You have not made it clear whether you are creating additional threads and whether you are accessing the socket from a thread that did not create it.
You have already been given a link that discusses what to do if that is the problem, but you replied «I do not know how this article can help me.» Why not?
My first response in this thread asked «Did you call a socket function from a thread that did not create the socket?» You have not answered that question. I can’t see how to help you further without a clearer description of what you are doing in your code.
-
Thanks Jesse for the reply. I am still working on this problem. I tried adding AfxSocketInit in all threads, but the problem is the same. Any ideas
about it? It will be very appreciated ! -
Also I researched lots of articles/posts for this error, and the suggestion is always «attach» and «detach». But on these articles/posts, no any people say that they can finally succeed in using CSocket in their application. The example code is just from
two articles from Microsoft, but in fact they are only a piece of short code. Can anyone provide any information so that I can find a real sample multiple threads application that uses CSocket? Thanks a lot.Debug Assertion Failed !
f:ddvctoolsvc7libsshipatlmfcsrcmfcsockcore.cpp line: 947
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.SocketErrorCodereturns a value from theSocketErrorenum. The numerical values of the enum elements always correspond to the Windows socket error codes.SocketException.ErrorCodealways returnsSocketException.NativeErrorCode.SocketException.NativeErrorCodeon .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core,SocketException.NativeErrorCodeequals the corresponding native error code from the current operating system.
A few practical recommendations:
- If you want to write portable code, always use
SocketException.SocketErrorCodeand compare it with the values ofSocketError. 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<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.SocketErrorCodereturns a value from theSocketErrorenum. The numerical values of the enum elements always correspond to the Windows socket error codes.SocketException.ErrorCodealways returnsSocketException.NativeErrorCode.SocketException.NativeErrorCodeon .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core,SocketException.NativeErrorCodeequals the corresponding native error code from the current operating system.
A few practical recommendations:
- If you want to write portable code, always use
SocketException.SocketErrorCodeand compare it with the values ofSocketError. 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
Содержание
- Troubleshooting connection issues
- Problem: the socket is not able to connect
- You are trying to reach a plain WebSocket server
- The server is not reachable
- The client is not compatible with the version of the server
- The server does not send the necessary CORS headers
- You didn’t enable sticky sessions (in a multi server setup)
- The request path does not match on both sides
- Problem: the socket gets disconnected
- The browser tab was minimized and heartbeat has failed
- The client is not compatible with the version of the server
- You are trying to send a huge payload
- Problem: the socket is stuck in HTTP long-polling
- Server API
- Server
- new Server(httpServer [, options] )
- new Server(port [, options] )
- How Socket Error Codes Depend on Runtime and Operating System
- Sockets and error codes
- Digging into the problem
- SocketErrorCode
- NativeErrorCode
- ErrorCode
- Writing cross-platform socket error handling
- Overview of the native error codes
- Summary
Troubleshooting connection issues
The Admin UI can give you additional insights about the status of your Socket.IO deployment.
Problem: the socket is not able to connect
You are trying to reach a plain WebSocket server
As explained in the «What Socket.IO is not» section, the Socket.IO client is not a WebSocket implementation and thus will not be able to establish a connection with a WebSocket server, even with transports: [«websocket»] :
The server is not reachable
Please make sure the Socket.IO server is actually reachable at the given URL. You can test it with:
which should return something like this:
If that’s not the case, please check that the Socket.IO server is running, and that there is nothing in between that prevents the connection.
Note: v1/v2 servers (which implement the v3 of the protocol, hence the EIO=3 ) will return something like this:
The client is not compatible with the version of the server
Here is the compatibility table for the JS client:
| JS Client version | Socket.IO server version | |||
|---|---|---|---|---|
| 1.x | 2.x | 3.x | 4.x | |
| 1.x | YES | NO | NO | NO |
| 2.x | NO | YES | YES 1 | YES 1 |
| 3.x | NO | NO | YES | YES |
| 4.x | NO | NO | YES | YES |
Here is the compatibility table for the Java client:
| Java Client version | Socket.IO server version | ||
|---|---|---|---|
| 2.x | 3.x | 4.x | |
| 1.x | YES | YES 1 | YES 1 |
| 2.x | NO | YES | YES |
Here is the compatibility table for the Swift client:
| Swift Client version | Socket.IO server version | ||
|---|---|---|---|
| 2.x | 3.x | 4.x | |
| v15.x | YES | YES 1 | YES 2 |
| v16.x | YES 3 | YES | YES |
[1] Yes, with allowEIO3: true (server) and .connectParams([«EIO»: «3»]) (client):
[3] Yes, with .version(.two) (client):
The server does not send the necessary CORS headers
If you see the following error in your console:
It probably means that:
- either you are not actually reaching the Socket.IO server (see above)
- or you didn’t enable Cross-Origin Resource Sharing (CORS) on the server-side.
Please see the documentation here.
You didn’t enable sticky sessions (in a multi server setup)
When scaling to multiple Socket.IO servers, you need to make sure that all the requests of a given Socket.IO session reach the same Socket.IO server. The explanation can be found here.
Failure to do so will result in HTTP 400 responses with the code:
Please see the documentation here.
The request path does not match on both sides
By default, the client sends — and the server expects — HTTP requests with the «/socket.io/» request path.
This can be controlled with the path option:
In that case, the HTTP requests will look like /my-custom-path/?EIO=4&transport=polling[&. ] .
means the client will try to reach the namespace named «/my-custom-path/», but the request path will still be «/socket.io/».
Problem: the socket gets disconnected
First and foremost, please note that disconnections are common and expected, even on a stable Internet connection:
- anything between the user and the Socket.IO server may encounter a temporary failure or be restarted
- the server itself may be killed as part of an autoscaling policy
- the user may lose connection or switch from WiFi to 4G, in case of a mobile browser
- the browser itself may freeze an inactive tab
That being said, the Socket.IO client will always try to reconnect, unless specifically told otherwise.
Possible explanations for a disconnection:
The browser tab was minimized and heartbeat has failed
When a browser tab is not in focus, some browsers (like Chrome) throttle JavaScript timers, which could lead to a disconnection by ping timeout in Socket.IO v2, as the heartbeat mechanism relied on setTimeout function on the client side.
As a workaround, you can increase the pingTimeout value on the server side:
Please note that upgrading to Socket.IO v4 (at least socket.io-client@4.1.3 , due to this) should prevent this kind of issues, as the heartbeat mechanism has been reversed (the server now sends PING packets).
The client is not compatible with the version of the server
Since the format of the packets sent over the WebSocket transport is similar in v2 and v3/v4, you might be able to connect with an incompatible client (see above), but the connection will eventually be closed after a given delay.
So if you are experiencing a regular disconnection after 30 seconds (which was the sum of the values of pingTimeout and pingInterval in Socket.IO v2), this is certainly due to a version incompatibility.
You are trying to send a huge payload
If you get disconnected while sending a huge payload, this may mean that you have reached the maxHttpBufferSize value, which defaults to 1 MB. Please adjust it according to your needs:
A huge payload taking more time to upload than the value of the pingTimeout option can also trigger a disconnection (since the heartbeat mechanism fails during the upload). Please adjust it according to your needs:
Problem: the socket is stuck in HTTP long-polling
In most cases, you should see something like this:
- the Engine.IO handshake (contains the session ID — here, zBjrh. AAAK — that is used in subsequent requests)
- the Socket.IO handshake request (contains the value of the auth option)
- the Socket.IO handshake response (contains the Socket#id)
- the WebSocket connection
- the first HTTP long-polling request, which is closed once the WebSocket connection is established
If you don’t see a HTTP 101 Switching Protocols response for the 4th request, that means that something between the server and your browser is preventing the WebSocket connection.
Please note that this is not necessarily blocking since the connection is still established with HTTP long-polling, but it is less efficient.
You can get the name of the current transport with:
Источник
Server API
Server
Exposed by require(‘socket.io’) .
new Server(httpServer [, options] )
- httpServer (http.Server) the server to bind to.
- options (Object)
Works with and without new :
| Option | Default value | Description |
|---|---|---|
| path | /socket.io | name of the path to capture |
| serveClient | true | whether to serve the client files |
| adapter | — | the adapter to use. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter |
| origins | * | the allowed origins |
| parser | — | the parser to use. Defaults to an instance of the Parser that ships with socket.io. See socket.io-parser. |
Available options for the underlying Engine.IO server:
| Option | Default value | Description |
|---|---|---|
| pingTimeout | 5000 | how many ms without a pong packet to consider the connection closed |
| pingInterval | 25000 | how many ms before sending a new ping packet |
| upgradeTimeout | 10000 | how many ms before an uncompleted transport upgrade is cancelled |
| maxHttpBufferSize | 10e7 | how many bytes or characters a message can be, before closing the session (to avoid DoS). |
| allowRequest | A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: fn(err, success) , where success is a boolean value where false means that the request is rejected, and err is an error code. | |
| transports | [‘polling’, ‘websocket’] | transports to allow connections to |
| allowUpgrades | true | whether to allow transport upgrades |
| perMessageDeflate | false | Whether to enable the permessage-deflate extension for the WebSocket transport. This extension is known to add a significant overhead in terms of performance and memory consumption, so we suggest to only enable it if it is really needed. Defaults to false since version 2.4.0 . |
| httpCompression | true | parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable. |
| cookie | io | name of the HTTP cookie that contains the client sid to send as part of handshake response headers. Set to false to not send one. |
| cookiePath | / | path of the above cookie option. If false, no path will be sent, which means browsers will only send the cookie on the engine.io attached path ( /engine.io ). Set false to not save io cookie on all requests. |
| cookieHttpOnly | true | if true HttpOnly io cookie cannot be accessed by client-side APIs, such as JavaScript. This option has no effect if cookie or cookiePath is set to false . |
| wsEngine | ws | what WebSocket server implementation to use. Specified module must conform to the ws interface (see ws module api docs). Default value is ws . An alternative c++ addon is also available by installing the eiows module. |
Among those options:
The pingTimeout and pingInterval parameters will impact the delay before a client knows the server is not available anymore. For example, if the underlying TCP connection is not closed properly due to a network issue, a client may have to wait up to pingTimeout + pingInterval ms before getting a disconnect event.
The order of the transports array is important. By default, a long-polling connection is established first, and then upgraded to WebSocket if possible. Using [‘websocket’] means there will be no fallback if a WebSocket connection cannot be opened.
new Server(port [, options] )
- port (Number) a port to listen to (a new http.Server will be created)
- options (Object)
See above for the list of available options .
Источник
How Socket Error Codes Depend on Runtime and Operating System
Table of Contents
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:
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:
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 :
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 ):
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):
These values correspond to the Windows Sockets Error Codes.
NativeErrorCode
In .NET Framework and Mono, SocketErrorCode and NativeErrorCode always have the same values:
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
The ErrorCode property is the most boring one, as it always returns NativeErrorCode .
.NET Framework, Mono 6.8.0.105:
Writing cross-platform socket error handling
Circling back to the original method we started this post with, we rewrote ShouldRetryConnection as follows:
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:
We executed this program on Windows, Linux, and macOS. Here are the aggregated results:
| SocketError | Windows | Linux | macOS |
| Success | |||
| 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:
Источник
windows — python socket: winerror 10056 —
i’ve read throught introduction python sockets: http://docs.python.org/3.3/howto/sockets.html
this server
import socket serversocket=socket.socket(socket.af_inet,socket.sock_stream) serversocket.bind(("localhost",8000)) serversocket.listen(5) while true: (client,addr)=serversocket.accept() data=serversocket.recv(1024) print(data.decode("utf-8"))
and client
import socket s=socket.socket(socket.af_inet, socket.sock_stream) s.connect(("localhost",8000))
the idea server prints data sent client. can see, intended encode message strings bytes utf-8. never came far.
with server script running, typed client lines 1 one idle python shell. after third line, error prompted up. since i’m german, vague translation. error message sound different if can reproduce error
traceback (most recent call last): file «», line 1, in s.connect((«localhost»,8000)) oserror: [winerror 10056] connection attempt targeted connected socket.
how can solve error ? server adapted, client exact code tutorial. , error seens rather strange, after want socket connected — server . @ first thought somehow there sockets connected server restarting , typing client code again lead same result.
you want receive on client socket, , close client socket when client closes. process 1 client @ time, note needs message protocol implemented know has complete message decode:
import socket serversocket = socket.socket() serversocket.bind(('',8000)) serversocket.listen(5) while true: client,addr = serversocket.accept() while true: data = client.recv(1024) if not data: break print(data.decode('utf8') # note might not contain complete utf-8 char. client.close()
Popular posts from this blog
html — Border-Radius is not Aligning Properly —
i trying create div rounded corners. inside div contains additional content fill height of div. i’ve noticed there visual corruption @ each corner of rounded div. looks me corner of outer div lightly larger inner div. according code, border-radius of both divs should identical. example of issue: http://jsfiddle.net/mrzaf/4/ image of issue: http://imgur.com/ph6ihlc <div class=»a-a»> <div class=»a-b»>content in here</div> </div> <br><br> <div class=»b-a»> <div class=»b-b»>content in here</div> </div> div.a-a { background:red; border-radius:10px; width:400px; } div.a-b { background:aqua; border-radius:10px; height:200px; } div.b-a { background:red; border-radius:10px; width:400px; overflow:hidden; } div.b-b { background:aqua; width:400px; height:200px; } there couple of option this. first option : increase border-radius of parent container div.a-a { b
jquery — How can I dynamically add a browser tab? —
since using iframes house external pages are, accounts «not preferred method» , disallowed sites (flickr, one), want dynamically generate browser tabs. e.g., when user submits form, want dynamically generate tab on browser in response submitted. e.g., might want add new tab url like: http://www.bigsurgarrapata.com/contact how in jquery? you want form target attribute action attribute. http://www.w3schools.com/tags/att_form_target.asp browsers have ultimate control on result of target attribute open new tab value of _blank. <form action=»contact_submit.php» target=»_blank» method=»post»>
javascript — google.elements.newsShow display Time not working —
i trying use google newsshow api display news in html app. here code <html xmlns=»http://www.w3.org/1999/xhtml»> <head> <meta http-equiv=»content-type» content=»text/html; charset=utf-8″/> <title>google ajax search api sample</title> <script src=»http://www.google.com/jsapi?key=aizasya5m1nc8ws2bbmprwku5gfradvd_hgq6g0″ type=»text/javascript»></script> <script type=»text/javascript»> google.load(«elements», «1», {packages : [«newsshow»]}); function onload() { // set display time 2 seconds, , transition time 100 ms var options = { «querylist» : [ { «title» : «indian news», «topic» : «n», «ned» : «in» } ], «displaytime» : 1000, «transitiontime» : 50 } var content = document.getelem



