hello,I am having the same problem,
C:UsersgeasyPycharmProjectstmpflask-chatvenvScriptspython.exe C:/Users/geasy/PycharmProjects/tmp/flask-chat/manage.py
(6120) wsgi starting up on http://127.0.0.1:80
(6120) accepted ('127.0.0.1', 56135)
(6120) accepted ('127.0.0.1', 56136)
(6120) accepted ('127.0.0.1', 56137)
(6120) accepted ('127.0.0.1', 56138)
(6120) accepted ('127.0.0.1', 56139)
(6120) accepted ('127.0.0.1', 56140)
(6120) accepted ('127.0.0.1', 56144)
ce05223a46814122a8c11782b2419f85
ce05223a46814122a8c11782b2419f85
Traceback (most recent call last):
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletgreenpool.py", line 88, in _spawn_n_impl
func(*args, **kwargs)
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletwsgi.py", line 734, in process_request
proto.__init__(sock, address, self)
File "C:UsersgeasyAppDataLocalProgramsPythonPython35libsocketserver.py", line 683, in __init__
self.finish()
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletwsgi.py", line 651, in finish
greenio.shutdown_safe(self.connection)
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletgreeniobase.py", line 479, in shutdown_safe
return sock.shutdown(socket.SHUT_RDWR)
OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。
29a7aa9376414bd5aa8e3425d441b5e3
(6120) accepted ('127.0.0.1', 56146)
Traceback (most recent call last):
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletgreenpool.py", line 88, in _spawn_n_impl
func(*args, **kwargs)
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletwsgi.py", line 734, in process_request
proto.__init__(sock, address, self)
File "C:UsersgeasyAppDataLocalProgramsPythonPython35libsocketserver.py", line 683, in __init__
self.finish()
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletwsgi.py", line 651, in finish
greenio.shutdown_safe(self.connection)
File "C:UsersgeasyPycharmProjectstmpflask-chatvenvlibsite-packageseventletgreeniobase.py", line 479, in shutdown_safe
return sock.shutdown(socket.SHUT_RDWR)
OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。
the log consists of two parts, the first part is the normal exit, the second part is directly close the browser.
class Joined(Namespace):
def on_connect(self):
print(request.sid)
room = session.get('room')
count = redis_db.incr("count")
emit('count', {'count': count}, room=room)
def on_joined(self, message):
name = session.get('name')
room = session.get('room')
join_room(room)
emit('status', {'message': '{}:enter room.'.format(name)}, room=room)
def on_admin(self, message):
room = session.get('room')
emit('message', {"message": message['message']}, room=room)
def on_broad(self, message):
emit('message', {"message": "broadcast message:{}".format(message['message'])}, broadcast=True)
def on_left(self, message):
room = session.get('room')
leave_room(room)
print(request.sid)
emit('status', {'message': '{} leave room.'.format(session['name'])}, room=room)
venv:
appdirs==1.4.0
click==6.7
enum-compat==0.0.2
eventlet==0.20.1
Flask==0.12
Flask-SocketIO==2.8.4
greenlet==0.4.12
itsdangerous==0.24
Jinja2==2.9.5
MarkupSafe==0.23
packaging==16.8
pyparsing==2.1.10
python-engineio==1.2.2
python-socketio==1.7.1
redis==2.10.5
six==1.10.0
Werkzeug==0.11.15
looking forward to your reply,thanks!
Добрый день изучаю python, поднял сайт на хостинге, но он начал выдавать ошибку которую никак не могу разобрать. В чем может быть проблема?
2015-11-02 21:57:44 +0000] [31789] [ERROR] Socket error processing request.
Traceback (most recent call last):
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle
self.handle_request(listener, req, client, addr)
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 187, in handle_request
six.reraise(exc_info[0], exc_info[1], exc_info[2])
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 171, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
response = self.get_response(request)
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/handlers/base.py", line 180, in get_response
'request': request
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/logging/__init__.py", line 1154, in error
self._log(ERROR, msg, args, **kwargs)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/logging/__init__.py", line 1246, in _log
self.handle(record)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/logging/__init__.py", line 1256, in handle
self.callHandlers(record)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/logging/__init__.py", line 1293, in callHandlers
hdlr.handle(record)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/logging/__init__.py", line 740, in handle
self.emit(record)
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/utils/log.py", line 129, in emit
connection=self.connection())
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/mail/__init__.py", line 98, in mail_admins
mail.send(fail_silently=fail_silently)
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/mail/message.py", line 283, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 92, in send_messages
new_conn_created = self.open()
File "/home/h22923/data/.pythonbrew/venvs/Python-2.7/mysite/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 50, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/home/h22923/data/.pythonbrew/pythons/Python-2.7/lib/python2.7/socket.py", line 567, in create_connection
raise error, msg
error: [Errno 110] Connection timed out
Содержание
- An error occurred while processing your request, что делать?
- Что такое An error occurred while processing your request
- Как исправить ошибку An error occurred
- Заключение
- [ERROR] Socket error processing request. #160
- Comments
- 12 Ways to Fix An Error Occurred While Processing Your Request
- We’ve tested all the solutions from this article
- Why am I getting An error occurred while processing your request?
- How do you fix An error has occurred while processing your request?
- An error occurred while processing your request on Chrome
- 1. Try another browser
- Opera
- 2. Delete your browser cache to fix
- 3. Delete the SSL certificate
- 4. Try visiting a non-encrypted version of the website
- 5. Disable the HTTPS Everywhere extension
- Error occurred while processing your request. Please try again later on OpenSea
- An error occurred while processing your request on TikTok
- An error occurred while processing your request on Steam
- An error occurred while processing your request on Xbox
- An error occurred while processing your request. Reference #30
- An error occurred while processing your request on Facebook
- An error occurred while processing your request reference 97
- Wait for the website administrator to fix this problem
An error occurred while processing your request, что делать?
Ряд пользователей браузеров при переходе на какой-либо сайт (наиболее часто данная проблема встречается на сайте Steam) могут столкнуться с ошибкой и соответствующим сообщением «An error occurred while processing your request». Обновление страницы проблемного сайта обычно ничего не даёт, пользователь сталкивается с упомянутой проблемой вновь и вновь. В этом материале я расскажу, что это за сообщение, при каких условиях появляется данная проблема, и как исправить её на вашем ПК.
Что такое An error occurred while processing your request
В переводе с английского языка текст данной ошибки звучит как «Произошла ошибка во время обработки вашего запроса». Как уже упоминалось выше, наиболее часто на возникновение данной ошибки жалуются пользователи Steam, которые при переходе на данный сайт встречают описанную дисфункцию.
При этом данная ошибка может встречаться и на других ресурсах, и в абсолютном большинстве случаев имеет браузерную основу (пользователи различных онлайн-программ практически с ней не сталкиваются).
Причины данной ошибки следующие:
- Сбой или перегрузка сервера, обрабатывающего ваш запрос;
- Случайный сбой вашего ПК;
- Кэш вашего браузера повреждён;
- Ошибка SSL-сертификата вашего браузера;
- Проблемы с HTTPS-протоколом у ряда сайтов;
- Проблема с HTTPS-расширениями вашего браузера (например, с «HTTPS Everywhere»).
После определения причин дисфункции перейдём к описанию того, как избавиться от ошибки Sorry, an error occurred while processing your request.
Как исправить ошибку An error occurred
Итак, вы встретились с упомянутой проблемой и думаете, как её устранить. Рекомендую выполнить следующий ряд действий:
- Попробуйте просто перезагрузить свой компьютер. Это помогает чаще, чем может показаться;
- Немного подождите. Во многих случаях (особенно это касается пользователей Steam) сервера бывают перегружены или «упали», потому необходимо некоторое время для решения проблемы администрацией сервера. В подобных случаях нужно немного подождать (часто хватает и суток) чтобы проблема была решена;
- Очистите кэш и куки вашего браузера. К примеру, в браузере Мозилла это делается переходом в «Настройки», затем в закладку «Приватность», и кликом на «Удалить вашу недавнюю историю». В открывшимся окне «Удаление истории» в «Подробности» поставьте галочку на «Кэш» и удалите последний;
Заключение
В данном материале мной была рассмотрена тема «An error occurred while processing your request, что делать», обозначены причины данной проблемы и намечены пути её решения. В большинстве случаев данная ошибка возникает из-за перегрузки или «падения» серверов, и от пользователя требуется немного подождать, дабы всё пришло в норму. В иных же случаях попробуйте выполнить очистку кэша вашего браузера, так как именно этот совет оказался весьма эффективным в решении данной проблемы на пользовательских ПК.
Источник
[ERROR] Socket error processing request. #160
I get the following error every now and then when running with gunicorn. I am not sure why or when this happens.
The text was updated successfully, but these errors were encountered:
Do things continue to work after this error?
Could this be happening when you close a browser tab that was connected to the server?
Yea, everything continues to work fine. This happens when I only have one connection open as well.
I thought it may be because of multiple gunicorn workers so I tried with only one worker. Same thing happens.
This usually happens when a connection is closed by the client. This can happen when running long-polling HTTP requests if you close the tab that the application was on, or also if you hit refresh. The problem is that when the long request ends gunicorn tries to write the response to the socket, but finds that the socket is gone because it was closed by the client.
If you think this description matches the problem, then I would not worry about it. It may be a good idea to report it to gunicorn, if you find a way to reliably reproduce it.
I see that’s the long-polling request is finished and the connection is upgraded to websocket. And whenever a client leaves, I see that disconnect event is firing properly. Would your response still be the case in this scenario?
Well, it’s really hard to be sure. The stack trace clearly points to an HTTP request, not WebSocket. I can’t really tell if this is a long-polling request or a regular request, but you can see that it comes from the wsgi module. The failure occurred when gunicorn was trying to write the HTTP response of this request to the socket, in particular while it tried to write the headers.
I can’t really say more than that from the stack trace, this is clearly internal to gunicorn. If you say that the connection was upgraded to WebSocket before this happened, then it’s odd that there are still HTTP request flying (assuming your application doesn’t still do some Ajax on the side that is).
So as I said before, it would be good to try to identify what actions are you taking that trigger this crash.
I’ll look into this more later. In the meantime, here’s my code:
Источник
12 Ways to Fix An Error Occurred While Processing Your Request
We’ve tested all the solutions from this article
- No matter what browser, you choose, certain errors are common among them.
- Errors processing requests could be related to cookies or cache, Internet connectivity, and more.
- Also, the error could be encountered on mobile apps or other platforms, though the fixes remain pretty much the same.
The Internet is an everyday part of our lives, and most of us use it on a daily basis. And, one of the common problems we encounter with it is the An error occurred while processing your request issue.
This is no ordinary error and can be encountered on several apps and even different platforms. The worst part, the error message doesn’t divulge what’s actually causing it, which makes it all the more difficult to resolve things.
In case you have been trying to find a solution, read the following sections to learn all about the An error occurred while processing your request issue, and the fixes that actually worked for users.
Why am I getting An error occurred while processing your request?
When you encounter this error, it’s most likely that the application or website’s network is down. And, there’s nothing you can do about it! You will have to simply wait for a while until it gets fixed by the backend team.
Also, corrupt browser cache or cookies too can lead to this error, along with a few extensions that modify the way your computer interacts with the website or platform throwing this error.
Besides, the error message might be slightly changed on different platforms. Some users also saw the message An error occurred while processing your request. Please try after some time. If the problem persists, please contact the helpdesk.
But no matter where you encounter it, we have listed the most effective solutions for the error on all known platforms in the following section.
How do you fix An error has occurred while processing your request?
An error occurred while processing your request on Chrome
1. Try another browser
If your current web browser continues to give you a hard time with error messages, then we recommend you try another one until you remediate the problem.
One tool that scores high marks in the stability department is Opera, and this is thanks to the ultra-modern Chromium engine that it uses, which it shares with Google Chrome and Edge.
It is lightweight and has the ability to be greatly altered, both visually and functionally, via extensions. If that isn’t enough, then maybe the built-in VPN and ad-blocker will convince you to give this browser a shot.
Opera
Enjoy a stable and error-free browsing experience with teh help of this fantastic and ultra-lightweight web browser.
2. Delete your browser cache to fix
- Launch Chrome, and press Ctrl + Shift + Delete to open the Clear browsing data window.
- Select All time from the Time range dropdown menu.
- Now, tick all the checkboxes here, and click on Clear data.
Users reported this error while trying to access certain websites, and according to them, the solution was to remove browsing cookies.
After clearing the cache, restart your browser and check if the error is resolved.
If the problem still persists, there might be an issue with the website itself, and the only thing that you can do is to contact the website administrator.
3. Delete the SSL certificate
This error can appear if your SSL certificate is expired, and one way to fix it is to delete the certificate and recreate it again.
Users reported that after deleting and recreating the security certificate the issue was completely resolved, so be sure to try that.
According to users, certain certificates will last only a year, so you’ll have to manually remove them and recreate them.
4. Try visiting a non-encrypted version of the website
Many websites use HTTPS protocol in order to encrypt their traffic and to protect the privacy of their users.
Unfortunately, some websites might have problems with HTTPS protocol, so you might want to use unencrypted HTTP protocol instead.
To do that, look at your website’s address, and if it has https at the beginning, simply change it to http and press Enter .
5. Disable the HTTPS Everywhere extension
As we already mentioned, the HTTPS protocol encrypts your data and protects your privacy, but not all websites support HTTPS.
To avoid this limitation, many users rely on third-party browser extensions such as HTTPS Everywhere.
This extension forces websites to use HTTPS protocol instead of HTTP, but that can lead to some problems.
Some websites don’t support HTTPS protocol, and by forcefully using this protocol you can cause An error occurred while processing your request error to appear.
One of the simplest ways to fix this problem is to disable the HTTPS Everywhere extension for the website that is giving you this problem.
Expert tip:
SPONSORED
Some PC issues are hard to tackle, especially when it comes to corrupted repositories or missing Windows files. If you are having troubles fixing an error, your system may be partially broken.
We recommend installing Restoro, a tool that will scan your machine and identify what the fault is.
Click here to download and start repairing.
Alternatively, you can remove the extension from the browser altogether, and this would fix the An error occurred while processing your request issue.
Error occurred while processing your request. Please try again later on OpenSea
The first thing you should do here is to wait for a while, and let the backend team fix issues, if any, with the platform. In case that doesn’t work, you may try clearing the browsing data.
Also, make sure that the NFT you are adding is a part of a collection, though OpenSea should do that automatically.
If you are receiving the error when accessing or using your wallet, try removing and reconnecting it to the OpenSea account, and the An error occurred while processing your request issue would be resolved.
Read more about this topic
An error occurred while processing your request on TikTok
When encountering the An error occurred while processing your request message, your primary approach should be to check if TikTok’s services are down, though that’s rare. To do that, use DownDetector, or other similar platforms available.
Also, simply logging out of your account and then signing back in is known to fix several problems. Besides, you can restart the device or reinstall the app itself, if nothing else works.
An error occurred while processing your request on Steam
Although this error appears on certain websites, many Steam games use a web launcher in order to start, so it’s not uncommon to see this error while trying to start certain games on Steam.
Therefore, if you’re getting An error occurred while processing your request error while trying to start a game using the web launcher, you might want to try running the game directly from your Steam folder.
Users reported that they were able to circumvent this problem simply by using the game’s .exe file to start it directly.
An error occurred while processing your request on Xbox
The error is encountered when accessing the official Xbox website and is largely limited to users in Europe. Though there have been instances of other users too coming across it.
To fix the error, the best solution would be to use an effective VPN software to reroute your connection. If that doesn’t work, you may switch to the Xbox app while the error gets resolved by the backend team.
An error occurred while processing your request. Reference #30
This is encountered while using the web version of a game and trying to log in via the Xbox account. When the game redirects you to official Xbox website, the error appears after you enter the login credentials.
A simple fix would be to clear the browsing data or use another device. Also, it could be a browser-related issue, and switching to another effective browser, like Opera GX which is developed for gaming and offers various customizations to boost the experience, would do the trick.
An error occurred while processing your request on Facebook
1. Log out and log back into your account
One of the simplest solutions that you can try if you’re getting An error occurred while processing your request error on Facebook is to log out and log back in after a few seconds.
This is a simple solution, and it might not work for everyone, but you can still try it out.
2. Clear your phone’s browsing data
Few users reported that they are unable to link their Facebook account with other third-party services due to this error, and one way to fix this problem is to go to your Facebook Mobile app and look for Clear your phone’s browsing data option.
After clearing the browsing data, this error should be fixed, and linking to third-party applications should work without any problems.
An error occurred while processing your request reference 97
Wait for the website administrator to fix this problem
Users reported An error occurred while processing your request reference 97 error while using Steam’s website. And, according to them, it seems that this issue is related to Steam and not to their computer.
If you encounter this error on Steam, wait a couple of hours for the website administrator to fix it.
An error occurred while processing your request error can be problematic and prevent you from accessing your favorite websites. We hope that you managed to fix this problem by using one of our solutions.
Also, if you are using a free VPN, the IP address might be marked as having suspicious activity. In this case, change it with a recommended VPN service.
Also, read our in-depth review of Opera GX which explores every intricate detail of the browser.
If you have any other queries or know of a method that’s not listed here, drop a comment below.
Still having issues? Fix them with this tool:
Источник
I have an Emby server running within Docker on a Debian Buster Linux server. I was investigating why a recording didn’t occur this evening and noticed the following happening
2020-05-20 11:50:27.284 Error HttpServer: Error processing request
*** Error Report ***
Version: 4.4.2.0
Command line: /system/EmbyServer.dll -programdata /config -ffdetect /bin/ffdetect -ffmpeg /bin/ffmpeg -ffprobe /bin/ffprobe -restartexitcode 3
Operating system: Unix 4.19.0.9
64-Bit OS: True
64-Bit Process: True
User Interactive: True
Runtime: file:///system/System.Private.CoreLib.dll
System.Environment.Version: 3.1.2
Processor count: 16
Program data path: /config
Application directory: /system
System.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object.
at Emby.Server.Implementations.Library.MediaSourceManager.GetLiveStreamWithDirectStreamProvider(String id, CancellationToken cancellationToken)
at Emby.Server.MediaEncoding.Api.BaseStreamingService.GetState(StreamRequest request, Boolean requiresOutputPath, CancellationToken cancellationToken)
at Emby.Server.MediaEncoding.Api.Hls.BaseHlsService.ProcessRequest(StreamRequest request)
at Emby.Server.Implementations.Services.ServiceController.GetTaskResult(Task task)
at Emby.Server.Implementations.Services.ServiceHandler.ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, RestPath restPath, String responseContentType, CancellationToken cancellationToken)
at Emby.Server.Implementations.HttpServer.HttpListenerHost.RequestHandler(IRequest httpReq, ReadOnlyMemory`1 urlString, ReadOnlyMemory`1 localPath, CancellationToken cancellationToken)
Source: Emby.Server.Implementations
TargetSite: Void MoveNext()
I’ve pulled the latest linuxserver/emby, recreated my Linux container, and restarted but have the same error. I’m not sure what issue it’s creating but it’s been going on for some time and at multiple times per minute, it’s really creating some huge log files.
This blog post was originally posted on JetBrains .NET blog.
Rider consists of several processes that send messages to each other via sockets. To ensure the reliability of the whole application, it’s important to properly handle all the socket errors. In our codebase, we had the following code which was adopted from Mono Debugger Libs and helps us communicate with debugger processes:
protected virtual bool ShouldRetryConnection (Exception ex, int attemptNumber)
{
var sx = ex as SocketException;
if (sx != null) {
if (sx.ErrorCode == 10061) //connection refused
return true;
}
return false;
}
In the case of a failed connection because of a “ConnectionRefused” error, we are retrying the connection attempt. It works fine with .NET Framework and Mono. However, once we migrated to .NET Core, this method no longer correctly detects the “connection refused” situation on Linux and macOS. If we open the SocketException
documentation, we will learn that this class has three different properties with error codes:
SocketError SocketErrorCode
: Gets the error code that is associated with this exception.int ErrorCode
: Gets the error code that is associated with this exception.int NativeErrorCode
: Gets the Win32 error code associated with this exception.
What’s the difference between these properties? Should we expect different values on different runtimes or different operating systems? Which one should we use in production? Why do we have problems with ShouldRetryConnection
on .NET Core? Let’s figure it all out!
Digging into the problem
Let’s start with the following program, which prints error code property values for SocketError.ConnectionRefused
:
var se = new SocketException((int) SocketError.ConnectionRefused);
Console.WriteLine((int)se.SocketErrorCode);
Console.WriteLine(se.ErrorCode);
Console.WriteLine(se.NativeErrorCode);
If we run it on Windows, we will get the same value on .NET Framework, Mono, and .NET Core:
SocketErrorCode | ErrorCode | NativeErrorCode | |
.NET Framework | 10061 | 10061 | 10061 |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 10061 | 10061 |
10061 corresponds to the code of the connection refused socket error code in Windows (also known as WSAECONNREFUSED
).
Now let’s run the same program on Linux:
SocketErrorCode | ErrorCode | NativeErrorCode | |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 111 | 111 |
As you can see, Mono returns Windows-compatible error codes. The situation with .NET Core is different: it returns a Windows-compatible value for SocketErrorCode (10061) and a Linux-like value for ErrorCode
and NativeErrorCode
(111).
Finally, let’s check macOS:
SocketErrorCode | ErrorCode | NativeErrorCode | |
Mono | 10061 | 10061 | 10061 |
.NET Core | 10061 | 61 | 61 |
Here, Mono is completely Windows-compatible again, but .NET Core returns 61 for ErrorCode
and NativeErrorCode
.
In the IBM Knowledge Center, we can find a few more values for the connection refused error code from the Unix world (also known as ECONNREFUSED
):
- AIX: 79
- HP-UX: 239
- Solaris: 146
For a better understanding of what’s going on, let’s check out the source code of all the properties.
SocketErrorCode
SocketException.SocketErrorCode
returns a value from the SocketError
enum. The numerical values of the enum elements are the same on all the runtimes (see its implementation in .NET Framework, .NET Core 3.1.3, and Mono 6.8.0.105):
public enum SocketError
{
SocketError = -1, // 0xFFFFFFFF
Success = 0,
OperationAborted = 995, // 0x000003E3
IOPending = 997, // 0x000003E5
Interrupted = 10004, // 0x00002714
AccessDenied = 10013, // 0x0000271D
Fault = 10014, // 0x0000271E
InvalidArgument = 10022, // 0x00002726
TooManyOpenSockets = 10024, // 0x00002728
WouldBlock = 10035, // 0x00002733
InProgress = 10036, // 0x00002734
AlreadyInProgress = 10037, // 0x00002735
NotSocket = 10038, // 0x00002736
DestinationAddressRequired = 10039, // 0x00002737
MessageSize = 10040, // 0x00002738
ProtocolType = 10041, // 0x00002739
ProtocolOption = 10042, // 0x0000273A
ProtocolNotSupported = 10043, // 0x0000273B
SocketNotSupported = 10044, // 0x0000273C
OperationNotSupported = 10045, // 0x0000273D
ProtocolFamilyNotSupported = 10046, // 0x0000273E
AddressFamilyNotSupported = 10047, // 0x0000273F
AddressAlreadyInUse = 10048, // 0x00002740
AddressNotAvailable = 10049, // 0x00002741
NetworkDown = 10050, // 0x00002742
NetworkUnreachable = 10051, // 0x00002743
NetworkReset = 10052, // 0x00002744
ConnectionAborted = 10053, // 0x00002745
ConnectionReset = 10054, // 0x00002746
NoBufferSpaceAvailable = 10055, // 0x00002747
IsConnected = 10056, // 0x00002748
NotConnected = 10057, // 0x00002749
Shutdown = 10058, // 0x0000274A
TimedOut = 10060, // 0x0000274C
ConnectionRefused = 10061, // 0x0000274D
HostDown = 10064, // 0x00002750
HostUnreachable = 10065, // 0x00002751
ProcessLimit = 10067, // 0x00002753
SystemNotReady = 10091, // 0x0000276B
VersionNotSupported = 10092, // 0x0000276C
NotInitialized = 10093, // 0x0000276D
Disconnecting = 10101, // 0x00002775
TypeNotFound = 10109, // 0x0000277D
HostNotFound = 11001, // 0x00002AF9
TryAgain = 11002, // 0x00002AFA
NoRecovery = 11003, // 0x00002AFB
NoData = 11004, // 0x00002AFC
}
These values correspond to the Windows Sockets Error Codes.
NativeErrorCode
In .NET Framework and Mono, SocketErrorCode
and NativeErrorCode
always have the same values:
public SocketError SocketErrorCode {
//
// the base class returns the HResult with this property
// we need the Win32 Error Code, hence the override.
//
get {
return (SocketError)NativeErrorCode;
}
}
In .NET Core, the native code is calculated in the constructor (see SocketException.cs#L20):
public SocketException(int errorCode) : this((SocketError)errorCode)
// ...
internal SocketException(SocketError socketError) : base(GetNativeErrorForSocketError(socketError))
The Windows implementation of GetNativeErrorForSocketError
is trivial (see SocketException.Windows.cs):
private static int GetNativeErrorForSocketError(SocketError error)
{
// SocketError values map directly to Win32 error codes
return (int)error;
}
The Unix implementation is more complicated (see SocketException.Unix.cs):
private static int GetNativeErrorForSocketError(SocketError error)
{
int nativeErr = (int)error;
if (error != SocketError.SocketError)
{
Interop.Error interopErr;
// If an interop error was not found, then don't invoke Info().RawErrno as that will fail with assert.
if (SocketErrorPal.TryGetNativeErrorForSocketError(error, out interopErr))
{
nativeErr = interopErr.Info().RawErrno;
}
}
return nativeErr;
}
TryGetNativeErrorForSocketError
should convert SocketError
to the native Unix error code.
Unfortunately, there exists no unequivocal mapping between Windows and Unix error codes. As such, the .NET team decided to create a Dictionary
that maps error codes in the best possible way (see SocketErrorPal.Unix.cs):
private const int NativeErrorToSocketErrorCount = 42;
private const int SocketErrorToNativeErrorCount = 40;
// No Interop.Errors are included for the following SocketErrors, as there's no good mapping:
// - SocketError.NoRecovery
// - SocketError.NotInitialized
// - SocketError.ProcessLimit
// - SocketError.SocketError
// - SocketError.SystemNotReady
// - SocketError.TypeNotFound
// - SocketError.VersionNotSupported
private static readonly Dictionary<Interop.Error, SocketError> s_nativeErrorToSocketError = new Dictionary<Interop.Error, SocketError>(NativeErrorToSocketErrorCount)
{
{ Interop.Error.EACCES, SocketError.AccessDenied },
{ Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse },
{ Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable },
{ Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported },
{ Interop.Error.EAGAIN, SocketError.WouldBlock },
{ Interop.Error.EALREADY, SocketError.AlreadyInProgress },
{ Interop.Error.EBADF, SocketError.OperationAborted },
{ Interop.Error.ECANCELED, SocketError.OperationAborted },
{ Interop.Error.ECONNABORTED, SocketError.ConnectionAborted },
{ Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused },
{ Interop.Error.ECONNRESET, SocketError.ConnectionReset },
{ Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired },
{ Interop.Error.EFAULT, SocketError.Fault },
{ Interop.Error.EHOSTDOWN, SocketError.HostDown },
{ Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available
{ Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable },
{ Interop.Error.EINPROGRESS, SocketError.InProgress },
{ Interop.Error.EINTR, SocketError.Interrupted },
{ Interop.Error.EINVAL, SocketError.InvalidArgument },
{ Interop.Error.EISCONN, SocketError.IsConnected },
{ Interop.Error.EMFILE, SocketError.TooManyOpenSockets },
{ Interop.Error.EMSGSIZE, SocketError.MessageSize },
{ Interop.Error.ENETDOWN, SocketError.NetworkDown },
{ Interop.Error.ENETRESET, SocketError.NetworkReset },
{ Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable },
{ Interop.Error.ENFILE, SocketError.TooManyOpenSockets },
{ Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable },
{ Interop.Error.ENODATA, SocketError.NoData },
{ Interop.Error.ENOENT, SocketError.AddressNotAvailable },
{ Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption },
{ Interop.Error.ENOTCONN, SocketError.NotConnected },
{ Interop.Error.ENOTSOCK, SocketError.NotSocket },
{ Interop.Error.ENOTSUP, SocketError.OperationNotSupported },
{ Interop.Error.EPERM, SocketError.AccessDenied },
{ Interop.Error.EPIPE, SocketError.Shutdown },
{ Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported },
{ Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported },
{ Interop.Error.EPROTOTYPE, SocketError.ProtocolType },
{ Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported },
{ Interop.Error.ESHUTDOWN, SocketError.Disconnecting },
{ Interop.Error.SUCCESS, SocketError.Success },
{ Interop.Error.ETIMEDOUT, SocketError.TimedOut },
};
private static readonly Dictionary<SocketError, Interop.Error> s_socketErrorToNativeError = new Dictionary<SocketError, Interop.Error>(SocketErrorToNativeErrorCount)
{
// This is *mostly* an inverse mapping of s_nativeErrorToSocketError. However, some options have multiple mappings and thus
// can't be inverted directly. Other options don't have a mapping from native to SocketError, but when presented with a SocketError,
// we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but
// SocketError.IOPending also maps closest to EINPROGRESS. As such, roundtripping won't necessarily provide the original value 100% of the time,
// but it's the best we can do given the mismatch between Interop.Error and SocketError.
{ SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM
{ SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE },
{ SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL },
{ SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT },
{ SocketError.AlreadyInProgress, Interop.Error.EALREADY },
{ SocketError.ConnectionAborted, Interop.Error.ECONNABORTED },
{ SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED },
{ SocketError.ConnectionReset, Interop.Error.ECONNRESET },
{ SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ },
{ SocketError.Disconnecting, Interop.Error.ESHUTDOWN },
{ SocketError.Fault, Interop.Error.EFAULT },
{ SocketError.HostDown, Interop.Error.EHOSTDOWN },
{ SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND },
{ SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH },
{ SocketError.InProgress, Interop.Error.EINPROGRESS },
{ SocketError.Interrupted, Interop.Error.EINTR },
{ SocketError.InvalidArgument, Interop.Error.EINVAL },
{ SocketError.IOPending, Interop.Error.EINPROGRESS },
{ SocketError.IsConnected, Interop.Error.EISCONN },
{ SocketError.MessageSize, Interop.Error.EMSGSIZE },
{ SocketError.NetworkDown, Interop.Error.ENETDOWN },
{ SocketError.NetworkReset, Interop.Error.ENETRESET },
{ SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH },
{ SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS },
{ SocketError.NoData, Interop.Error.ENODATA },
{ SocketError.NotConnected, Interop.Error.ENOTCONN },
{ SocketError.NotSocket, Interop.Error.ENOTSOCK },
{ SocketError.OperationAborted, Interop.Error.ECANCELED },
{ SocketError.OperationNotSupported, Interop.Error.ENOTSUP },
{ SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT },
{ SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT },
{ SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT },
{ SocketError.ProtocolType, Interop.Error.EPROTOTYPE },
{ SocketError.Shutdown, Interop.Error.EPIPE },
{ SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT },
{ SocketError.Success, Interop.Error.SUCCESS },
{ SocketError.TimedOut, Interop.Error.ETIMEDOUT },
{ SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE
{ SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing
{ SocketError.WouldBlock, Interop.Error.EAGAIN },
};
internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno)
{
return s_socketErrorToNativeError.TryGetValue(error, out errno);
}
Once we have an instance of Interop.Error
, we call interopErr.Info().RawErrno
. The implementation of RawErrno can be found in Interop.Errors.cs:
internal int RawErrno
{
get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")]
internal static extern int ConvertErrorPalToPlatform(Error error);
Here we are jumping to the native function SystemNative_ConvertErrorPalToPlatform that maps Error to the native integer code that is defined in errno.h. You can get all the values using the errno util. Here is a typical output on Linux:
$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 No such device or address
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EAGAIN 11 Resource temporarily unavailable
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Device or resource busy
EEXIST 17 File exists
EXDEV 18 Invalid cross-device link
ENODEV 19 No such device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Numerical result out of range
EDEADLK 35 Resource deadlock avoided
ENAMETOOLONG 36 File name too long
ENOLCK 37 No locks available
ENOSYS 38 Function not implemented
ENOTEMPTY 39 Directory not empty
ELOOP 40 Too many levels of symbolic links
EWOULDBLOCK 11 Resource temporarily unavailable
ENOMSG 42 No message of desired type
EIDRM 43 Identifier removed
ECHRNG 44 Channel number out of range
EL2NSYNC 45 Level 2 not synchronized
EL3HLT 46 Level 3 halted
EL3RST 47 Level 3 reset
ELNRNG 48 Link number out of range
EUNATCH 49 Protocol driver not attached
ENOCSI 50 No CSI structure available
EL2HLT 51 Level 2 halted
EBADE 52 Invalid exchange
EBADR 53 Invalid request descriptor
EXFULL 54 Exchange full
ENOANO 55 No anode
EBADRQC 56 Invalid request code
EBADSLT 57 Invalid slot
EDEADLOCK 35 Resource deadlock avoided
EBFONT 59 Bad font file format
ENOSTR 60 Device not a stream
ENODATA 61 No data available
ETIME 62 Timer expired
ENOSR 63 Out of streams resources
ENONET 64 Machine is not on the network
ENOPKG 65 Package not installed
EREMOTE 66 Object is remote
ENOLINK 67 Link has been severed
EADV 68 Advertise error
ESRMNT 69 Srmount error
ECOMM 70 Communication error on send
EPROTO 71 Protocol error
EMULTIHOP 72 Multihop attempted
EDOTDOT 73 RFS specific error
EBADMSG 74 Bad message
EOVERFLOW 75 Value too large for defined data type
ENOTUNIQ 76 Name not unique on network
EBADFD 77 File descriptor in bad state
EREMCHG 78 Remote address changed
ELIBACC 79 Can not access a needed shared library
ELIBBAD 80 Accessing a corrupted shared library
ELIBSCN 81 .lib section in a.out corrupted
ELIBMAX 82 Attempting to link in too many shared libraries
ELIBEXEC 83 Cannot exec a shared library directly
EILSEQ 84 Invalid or incomplete multibyte or wide character
ERESTART 85 Interrupted system call should be restarted
ESTRPIPE 86 Streams pipe error
EUSERS 87 Too many users
ENOTSOCK 88 Socket operation on non-socket
EDESTADDRREQ 89 Destination address required
EMSGSIZE 90 Message too long
EPROTOTYPE 91 Protocol wrong type for socket
ENOPROTOOPT 92 Protocol not available
EPROTONOSUPPORT 93 Protocol not supported
ESOCKTNOSUPPORT 94 Socket type not supported
EOPNOTSUPP 95 Operation not supported
EPFNOSUPPORT 96 Protocol family not supported
EAFNOSUPPORT 97 Address family not supported by protocol
EADDRINUSE 98 Address already in use
EADDRNOTAVAIL 99 Cannot assign requested address
ENETDOWN 100 Network is down
ENETUNREACH 101 Network is unreachable
ENETRESET 102 Network dropped connection on reset
ECONNABORTED 103 Software caused connection abort
ECONNRESET 104 Connection reset by peer
ENOBUFS 105 No buffer space available
EISCONN 106 Transport endpoint is already connected
ENOTCONN 107 Transport endpoint is not connected
ESHUTDOWN 108 Cannot send after transport endpoint shutdown
ETOOMANYREFS 109 Too many references: cannot splice
ETIMEDOUT 110 Connection timed out
ECONNREFUSED 111 Connection refused
EHOSTDOWN 112 Host is down
EHOSTUNREACH 113 No route to host
EALREADY 114 Operation already in progress
EINPROGRESS 115 Operation now in progress
ESTALE 116 Stale file handle
EUCLEAN 117 Structure needs cleaning
ENOTNAM 118 Not a XENIX named type file
ENAVAIL 119 No XENIX semaphores available
EISNAM 120 Is a named type file
EREMOTEIO 121 Remote I/O error
EDQUOT 122 Disk quota exceeded
ENOMEDIUM 123 No medium found
EMEDIUMTYPE 124 Wrong medium type
ECANCELED 125 Operation canceled
ENOKEY 126 Required key not available
EKEYEXPIRED 127 Key has expired
EKEYREVOKED 128 Key has been revoked
EKEYREJECTED 129 Key was rejected by service
EOWNERDEAD 130 Owner died
ENOTRECOVERABLE 131 State not recoverable
ERFKILL 132 Operation not possible due to RF-kill
EHWPOISON 133 Memory page has hardware error
ENOTSUP 95 Operation not supported
Note that errno
may be not available by default in your Linux distro. For example, on Debian, you should call sudo apt-get install moreutils
to get this utility.
Here is a typical output on macOS:
$ errno -ls
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted system call
EIO 5 Input/output error
ENXIO 6 Device not configured
E2BIG 7 Argument list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EDEADLK 11 Resource deadlock avoided
ENOMEM 12 Cannot allocate memory
EACCES 13 Permission denied
EFAULT 14 Bad address
ENOTBLK 15 Block device required
EBUSY 16 Resource busy
EEXIST 17 File exists
EXDEV 18 Cross-device link
ENODEV 19 Operation not supported by device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate ioctl for device
ETXTBSY 26 Text file busy
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Illegal seek
EROFS 30 Read-only file system
EMLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Numerical argument out of domain
ERANGE 34 Result too large
EAGAIN 35 Resource temporarily unavailable
EWOULDBLOCK 35 Resource temporarily unavailable
EINPROGRESS 36 Operation now in progress
EALREADY 37 Operation already in progress
ENOTSOCK 38 Socket operation on non-socket
EDESTADDRREQ 39 Destination address required
EMSGSIZE 40 Message too long
EPROTOTYPE 41 Protocol wrong type for socket
ENOPROTOOPT 42 Protocol not available
EPROTONOSUPPORT 43 Protocol not supported
ESOCKTNOSUPPORT 44 Socket type not supported
ENOTSUP 45 Operation not supported
EPFNOSUPPORT 46 Protocol family not supported
EAFNOSUPPORT 47 Address family not supported by protocol family
EADDRINUSE 48 Address already in use
EADDRNOTAVAIL 49 Can`t assign requested address
ENETDOWN 50 Network is down
ENETUNREACH 51 Network is unreachable
ENETRESET 52 Network dropped connection on reset
ECONNABORTED 53 Software caused connection abort
ECONNRESET 54 Connection reset by peer
ENOBUFS 55 No buffer space available
EISCONN 56 Socket is already connected
ENOTCONN 57 Socket is not connected
ESHUTDOWN 58 Can`t send after socket shutdown
ETOOMANYREFS 59 Too many references: can`t splice
ETIMEDOUT 60 Operation timed out
ECONNREFUSED 61 Connection refused
ELOOP 62 Too many levels of symbolic links
ENAMETOOLONG 63 File name too long
EHOSTDOWN 64 Host is down
EHOSTUNREACH 65 No route to host
ENOTEMPTY 66 Directory not empty
EPROCLIM 67 Too many processes
EUSERS 68 Too many users
EDQUOT 69 Disc quota exceeded
ESTALE 70 Stale NFS file handle
EREMOTE 71 Too many levels of remote in path
EBADRPC 72 RPC struct is bad
ERPCMISMATCH 73 RPC version wrong
EPROGUNAVAIL 74 RPC prog. not avail
EPROGMISMATCH 75 Program version wrong
EPROCUNAVAIL 76 Bad procedure for program
ENOLCK 77 No locks available
ENOSYS 78 Function not implemented
EFTYPE 79 Inappropriate file type or format
EAUTH 80 Authentication error
ENEEDAUTH 81 Need authenticator
EPWROFF 82 Device power is off
EDEVERR 83 Device error
EOVERFLOW 84 Value too large to be stored in data type
EBADEXEC 85 Bad executable (or shared library)
EBADARCH 86 Bad CPU type in executable
ESHLIBVERS 87 Shared library version mismatch
EBADMACHO 88 Malformed Mach-o file
ECANCELED 89 Operation canceled
EIDRM 90 Identifier removed
ENOMSG 91 No message of desired type
EILSEQ 92 Illegal byte sequence
ENOATTR 93 Attribute not found
EBADMSG 94 Bad message
EMULTIHOP 95 EMULTIHOP (Reserved)
ENODATA 96 No message available on STREAM
ENOLINK 97 ENOLINK (Reserved)
ENOSR 98 No STREAM resources
ENOSTR 99 Not a STREAM
EPROTO 100 Protocol error
ETIME 101 STREAM ioctl timeout
EOPNOTSUPP 102 Operation not supported on socket
ENOPOLICY 103 Policy not found
ENOTRECOVERABLE 104 State not recoverable
EOWNERDEAD 105 Previous owner died
EQFULL 106 Interface output queue is full
ELAST 106 Interface output queue is full
Hooray! We’ve finished our fascinating journey into the internals of socket error codes. Now you know where .NET is getting the native error code for each SocketException
from!
ErrorCode
The ErrorCode
property is the most boring one, as it always returns NativeErrorCode
.
.NET Framework, Mono 6.8.0.105:
public override int ErrorCode {
//
// the base class returns the HResult with this property
// we need the Win32 Error Code, hence the override.
//
get {
return NativeErrorCode;
}
}
In .NET Core 3.1.3:
public override int ErrorCode => base.NativeErrorCode;
Writing cross-platform socket error handling
Circling back to the original method we started this post with, we rewrote ShouldRetryConnection as follows:
protected virtual bool ShouldRetryConnection(Exception ex)
{
if (ex is SocketException sx)
return sx.SocketErrorCode == SocketError.ConnectionRefused;
return false;
}
There was a lot of work involved in tracking down the error code to check against, but in the end, our code is much more readable now. Adding to that, this method is now also completely cross-platform, and works correctly on any runtime.
Overview of the native error codes
In some situations, you may want to have a table with native error codes on different operating systems. We can get these values with the following code snippet:
var allErrors = Enum.GetValues(typeof(SocketError)).Cast<SocketError>().ToList();
var maxNameWidth = allErrors.Select(x => x.ToString().Length).Max();
foreach (var socketError in allErrors)
{
var name = socketError.ToString().PadRight(maxNameWidth);
var code = new SocketException((int) socketError).NativeErrorCode.ToString().PadLeft(7);
Console.WriteLine("| {name} | {code} |");
}
We executed this program on Windows, Linux, and macOS. Here are the aggregated results:
SocketError | Windows | Linux | macOS |
Success | 0 | 0 | 0 |
OperationAborted | 995 | 125 | 89 |
IOPending | 997 | 115 | 36 |
Interrupted | 10004 | 4 | 4 |
AccessDenied | 10013 | 13 | 13 |
Fault | 10014 | 14 | 14 |
InvalidArgument | 10022 | 22 | 22 |
TooManyOpenSockets | 10024 | 23 | 23 |
WouldBlock | 10035 | 11 | 35 |
InProgress | 10036 | 115 | 36 |
AlreadyInProgress | 10037 | 114 | 37 |
NotSocket | 10038 | 88 | 38 |
DestinationAddressRequired | 10039 | 89 | 39 |
MessageSize | 10040 | 90 | 40 |
ProtocolType | 10041 | 91 | 41 |
ProtocolOption | 10042 | 92 | 42 |
ProtocolNotSupported | 10043 | 93 | 43 |
SocketNotSupported | 10044 | 94 | 44 |
OperationNotSupported | 10045 | 95 | 45 |
ProtocolFamilyNotSupported | 10046 | 96 | 46 |
AddressFamilyNotSupported | 10047 | 97 | 47 |
AddressAlreadyInUse | 10048 | 98 | 48 |
AddressNotAvailable | 10049 | 99 | 49 |
NetworkDown | 10050 | 100 | 50 |
NetworkUnreachable | 10051 | 101 | 51 |
NetworkReset | 10052 | 102 | 52 |
ConnectionAborted | 10053 | 103 | 53 |
ConnectionReset | 10054 | 104 | 54 |
NoBufferSpaceAvailable | 10055 | 105 | 55 |
IsConnected | 10056 | 106 | 56 |
NotConnected | 10057 | 107 | 57 |
Shutdown | 10058 | 32 | 32 |
TimedOut | 10060 | 110 | 60 |
ConnectionRefused | 10061 | 111 | 61 |
HostDown | 10064 | 112 | 64 |
HostUnreachable | 10065 | 113 | 65 |
ProcessLimit | 10067 | 10067 | 10067 |
SystemNotReady | 10091 | 10091 | 10091 |
VersionNotSupported | 10092 | 10092 | 10092 |
NotInitialized | 10093 | 10093 | 10093 |
Disconnecting | 10101 | 108 | 58 |
TypeNotFound | 10109 | 10109 | 10109 |
HostNotFound | 11001 | -131073 | -131073 |
TryAgain | 11002 | 11 | 35 |
NoRecovery | 11003 | 11003 | 11003 |
NoData | 11004 | 61 | 96 |
SocketError | -1 | -1 | -1 |
This table may be useful if you work with native socket error codes.
Summary
From this investigation, we’ve learned the following:
SocketException.SocketErrorCode
returns a value from theSocketError
enum. The numerical values of the enum elements always correspond to the Windows socket error codes.SocketException.ErrorCode
always returnsSocketException.NativeErrorCode
.SocketException.NativeErrorCode
on .NET Framework and Mono always corresponds to the Windows error codes (even if you are using Mono on Unix). On .NET Core,SocketException.NativeErrorCode
equals the corresponding native error code from the current operating system.
A few practical recommendations:
- If you want to write portable code, always use
SocketException.SocketErrorCode
and compare it with the values 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
Today, in this write-up, I am going to share the resolution of an issue which is not a frequent one and will not come rapidly, but yeah I have seen this issue while working with the Selenium grid, so I am sharing this with you all.
Today, in this write-up, I am going to share the resolution of an issue which is not a frequent one and will not come rapidly, but yeah I have seen this issue while working with the Selenium grid, so I am sharing this with you all.
ERROR Stack Trace
Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:Usersmjain>cd DownloadsJar C:UsersmjainDownloadsJar>java -jar selenium-server-standalone-2.42.2.jar -role hub Sep 01, 2014 1:57:42 PM org.openqa.grid.selenium.GridLauncher main INFO: Launching a selenium grid server 2014-09-01 13:57:45.752:INFO:osjs.Server:jetty-7.x.y-SNAPSHOT 2014-09-01 13:57:45.907:INFO:osjsh.ContextHandler:started o.s.j.s.ServletContextHandler{/,null} 2014-09-01 13:57:45.939:INFO:osjs.AbstractConnector:Started SocketConnector@0.0.0.0:4444 Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:08 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:09 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy isAlive WARNING: Failed to check status of node: Permission denied: connect Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: I/O exception (java.net.SocketException) caught when processing request: Permission denied: connect Sep 01, 2014 2:26:14 PM org.apache.http.impl.execchain.RetryExec execute INFO: Retrying request Sep 01, 2014 2:26:14 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy isAlive WARNING: Failed to check status of node: Permission denied: connect Sep 01, 2014 2:26:14 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy onEvent WARNING: Marking the node as down. Cannot reach the node for 2 tries.
Steps which I have taken when I got this issue
- Step1 Start selenium grid hub
java -jar selenium-server-standalone-3.4.0.jar -role hub
- Step2 Start a node
java -Dwebdriver.chrome.driver=E:chromedriver.exe -jar selenium-server-standalone-3.4.0.jar -role node -hub http://192.168.1.XX:4444/grid/register
- Step 3 Start executing test scripts.
- Step4 You will get the above error.
Solution
You will get this error only and only when some other Virtual Private Network is connected on your machine. Such that there is some conflict in the IP which is causing the problems in re-directions of requests.
So to avoid this Error make sure you are not on any VPN connectivity, or for that matter, if you want to work on VPN then make sure you are providing the whole IP(192.168.1.23) rather than Host-name(localhost or MyMachine, etc).
Once you will apply any of the above steps then, you can easily get rid of this issue. This worked for me, I will be more than happy to answer your queries/feedback/revert over the same.
Khyati has more than 10 years of experience in quality assurance engineering.
Khyati has worked extensively on Manual and Automation testing of various technologies and domains like data quality. From last 6 years, She is leading QA Activities on Agile/Scrum projects while continuously contributing in playing role as a Scrum master, continuous integration, iteration planning, facilitating requirement analysis and closure.
On automation front, She has explored gui, web services and mobile automation.
Tools/ Technologies used:-
Selenium/WebDriver, Core Java, JUnit, TestNG, Maven, SoapUI. Jenkins, Appium, Selenium backed and selenium remote driver.
Have delve into android phone/tab of verison upto 6 (marshmallow), ios phone/i pad, and mobile websites
View all posts by Khyati Sehgal