nc – “Netcat”

My favorite tool of the day is nc, or Netcat.

Like most unix programs, it’s a well-documented single purpose application. From the man page:

The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP.  It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.  Unlike telnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.

This is particularly handy when debugging network applications. Instead of wondering whether bugs lie in your application code or in the server, you can simply point your application to nc to easily see what’s being sent across the wire.

To illustrate the simplicity, let’s send “Hello world” between terminal windows (this could be across the world almost as easily).

Start by opening a terminal window and typing “nc -l 4567”. This command tells netcat to listen for incoming TCP connections on port 4567.

Screen Shot 2013-11-13 at 10.37.33 PMNext, open a second terminal window and type “nc localhost 4567”. This command tells netcat to connect to localhost (the current machine) on port 4567. This connection will succeed because we’re the ones listening.Screen Shot 2013-11-13 at 10.39.30 PM

You’ll notice it looks like the program is hanging, but start typing into the terminal and press enter/return and you’ll see each line appear in the first terminal like magic.

Screen Shot 2013-11-13 at 10.42.10 PMScreen Shot 2013-11-13 at 10.42.13 PMKilling the second window will close the connection.

Additional applications for this include sending files over the connection (via netcat localhost 4567 < file.format).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s