SO_ERROR vs errno

To get a syscall socket error (e.g. recv ), which is better (at performance level)?

  • Use plain old errno
  • Or use SO_ERROR as getsockopt() optname?

I think errno (defined for __error() on my system) is faster because it is not a system call. I'm right?

Advantages of SO_ERROR: automatic reset error upon receipt, and we are sure that the error only affects our socket. It is safer.

Which, in your opinion, is better? Is there a performance difference between the two?

+6
source share
2 answers

Quote from Dan Bernstein :

Situation: you install a non-blocking socket and do connect (), which returns -1 / EINPROGRESS or -1 / EWOULDBLOCK. You select () a socket for recording. This returns as soon as the connection succeeds or fails. (Exception: in some older versions of Ultrix select () would not have noticed an error before a 75 second timeout.)

Question: What do you do after select () returns writeability? Did the connection fail? If so, how did this happen?

If the connection fails, the reason is hidden inside what is called so_error in the socket. Modern systems allow you to see so_error with getsockopt (, SO_ERROR,) ...

He further discusses the fact that getsockopt(,,SO_ERROR,,) is a modern invention that does not work on older systems and how to get an error code on such systems. But you probably should not worry about this if you are programming a Unix / Linux system released over the past 15 years.

The Linux SO_ERROR page for connect describes the same use of SO_ERROR .

So, if you are performing asynchronous socket operations, you may need to use SO_ERROR . Otherwise, just use errno .

+4
source

Unix Network Programming Guide:

If so_error is nonzero when the process invokes reading and there is no data to return, reading returns -1 with the errno variable set to so_error (p. 516 TCPv2). The value of so_error then reset is 0. If there is data queued for the socket, the data is returned by reading instead of the error condition. If so_error is nonzero when the write process is invoked, -1 is returned with errno set to so_error (p. 495). TCPv2), and so_error is reset to 0.

Thus, errno is the best choice if you do not want to get an error right before the data is fully retrieved.

0
source

All Articles