Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulate socket errors

Tags:

c++

sockets

How to simulate socket errors? (sometimes server or client disconnects because of some socket error and it is impossible to reproduce.) I was looking for a tool to do this, but I can't find one. Does anyone know either of a tool or has a code example on how to do this? (C# or C/C++)

like image 794
ra170 Avatar asked Jan 14 '10 20:01

ra170


People also ask

How do you simulate a socket error?

BUT, using a VM (virtual machine), you can easily do it - use the VM as a "client" to connect to your server application and then kill the VM with no warning (Power Off the virtual machine) - voilà a network error occurs.

What are the common causes of socket errors?

Socket errors can be caused by various issues including connectivity problems on the network, client or server computers or due to a firewall, antivirus or a proxy server. This error occurs when the socket connection to the remote server is denied.


2 Answers

Add a wrapper layer to the APIs you're using to access the sockets and have them fail rand() % 100 > x percent of the time.

like image 152
Terry Mahaffey Avatar answered Oct 23 '22 09:10

Terry Mahaffey


I had exactly the same problem this summer.

I had a custom Socket class and wanted to test what would happen if read or write threw an exception. I really wanted to mimic the Java mocking frameworks, and I did it like this:

I inherited the Socket class into a FakeSocket class, and created something called a SocketExpectation. Then, in the unit tests, I created fake sockets, set up the expectations and then passed that fake socket to the code I wanted to test.

The FakeSocket had these methods (stripped of unneeded details):

uint32_t write(buffer, length); // calls check
uint32_t read(buffer, length); // calls check 
bool matches();
void expect(expectation); 
uint32_t check(CallType, buffer, length) const; 

They're all pretty straight forward. check checks the arguments against the current expectation and if everything is according to plan, proceeds to perform the SocketExpectation requirement.

The SocketExpectation has this outline (also stripped):

typedef enum   { write, read } CallType;

SocketExpectation(CallType type);
SocketExpectation &with_arguments(void *a1, uint32_t a2); // expects these args
SocketExpectation &will_return(uint32_t value); 
SocketExpectation &will_throw(const char * e); // test error handling
bool matches(); 

I added more methods as I needed them. I would create it like this, then pass the fake socket to the relevant method:

fake_socket = FakeSocket();
fake_socket.expect(SocketExpectation(write).with_arguments(....).will_return(...));
fake_socket.expect(SocketExpectation(read).with_arguments(...).will_throw("something"));
like image 39
laura Avatar answered Oct 23 '22 09:10

laura