Monday, January 19, 2009

Using netcat to break TCP connections during testing

One of our devs developed a small ruby app that connects to a remote server over TCP and accepts an xml feed in return. This feed is then translated into our own TCP stream language and passed to a backend app. He needed to simulate a network / remote server outage to test the robustness of his code.

I initially thought that I could just set up an iptables packet filter on the firewall, but adding a quick DROP rule didn't work because the connection remains constantly established. Stopping and starting the ruby app got the packet filter to work, which proved that the DROP rule actually does work for new connections.

Another colleague suggested using a local netcat listener to bridge the TCP connection to the remote server, and point the ruby app at the local listener. Then just tear down the listener to simulate an outage.

The following example didn't work very well, because everything coming back from the other end just ended up in stdout.
nc -l -p 1234 | nc remote.server.com 1234

So I ended up using a fifo like this:
mkfifo backpipe; nc -l -p 1234 < backpipe | nc remote.server.com 1234 > backpipe

That works great and can just be killed with a CTRL-C to simulate a broken network, remote server outage, etc

No comments: