简体   繁体   中英

C# Resource temporarily unavailable with blocking socket on dotnet core on linux

I have some c# code that has worked for ages on windows but is suddenly failing when run on linux after dotnet core conversion.

The particular code involves manually opening a socket connection and implementing a timeout by temporarily setting the socket to non-blocking, to move past the Connect method, polling the socket until it's connected, but also with an exit path for a timeout.

When the non-blocking connect method is passed an exception is thrown which is saying "I would block here if I were a blocking socket" (technically referred to as "EAGAIN", for which the string "Resource temporarily unavailable" is tied). I catch that exception and if it's "WouldBlock", ignore the exception and move on (to polling for the connection to complete or the timeout to occur). On linux I am getting "Resource temporarily available" somehow even though I am catching this error code.

The native error codes for sockets are different on each OS, even differing on different flavors of unix. When we used MONO for cross platform, it automatically adapted the native error codes to windows error codes, so that they would match the SocketError enum. Dotnet core doesn't do this.

There are (now) three ways to get the error code for a SocketException.

  • ErrorCode (points directly at NativeErrorCode)
  • NativeErrorCode (returns the OS specific error code which will only match SocketError enum on windows)
  • SocketErrorCode (maps the error codes to windows error codes again, so they can be checked against the SocketError enum)

To be cross platform when checking SocketException error codes, use SocketException.SocketErrorCode and compare it to the SocketError enum.

A good article with more deep info: https://blog.jetbrains.com/dotnet/2020/04/27/socket-error-codes-depend-runtime-operating-system/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM