How to simulate an abnormal case for programming a socket / tcp in linux, for example, to end one side of the connection?

I am studying using SO_SNDTIMEO and SO_RCVTIMEO to check timeout. It is easy to use with reading . But when I want to check write timeout, it always returns successfully. Here is what I did: (all in lock mode)

  • close the client read socket and exit before starting the server write
  • complete the client before starting the server write
  • disconnect the server cable after accept , but before write

well, it seems that all these cases are writing , just returning successfully. I think the reason is that the port is a resource managed by os, and on the client side, after the program finishes, the tcp connection still shows FIN_WAIT2 status.

So, is there a convenient way to simulate some cases where a recording may receive errors such as EPIPE , EAGAIN ?

+6
source share
3 answers

How to get EAGAIN error?
To get the EAGAIN error, you need to use non-blocking sockets. With non-blocking sockets, you need to write huge amounts of data (and stop receiving data on the peer side) so that your internal TCP buffer is full and returns this error.

How to get EPIPE error message?
To get an EPIPE error message, you need to send a large amount of data after closing the socket on the partner side. You can get more information about the EPIPE error from this SO Link . I asked the Broken Pipe error question in the link provided, and the accepted answer gives a detailed explanation. It is important to note that in order to receive an EPIPE error, you must set the flags parameter to be sent to MSG_NOSIGNAL. Without this, abnormal sending can generate a SIGPIPE signal.

Additional note
Note that it is difficult to simulate a write failure, since TCP usually stores the data that you are trying to write to its internal buffer. Thus, if the internal buffer has enough space, then you will not get an error immediately. It’s best to try to write a lot of data. You can also try setting a smaller buffer size for sending with setsockopt with the SO_SNDBUF option

+5
source

You can simulate errors by inserting errors . For example, libfiu is an error injection library that comes with an example project that allows you to simulate errors from POSIX functions. It mainly uses LD_PRELOAD to enter a wrapper around regular system calls (including write ), and then the wrapper can be configured to either a real system call or return any error you need.

+5
source

You can set the size of the receive buffer to actually be very small on one side and send a large buffer on the other. Or, on the one hand, set up a small send buffer and try sending a large message.

Otherwise, the most common test (I think) is to let the server and client talk for a while, and then remove the network cable.

+1
source

Source: https://habr.com/ru/post/919005/


All Articles