nc or netcat utility is command line tool for debugging server or client network application. It can open TCP connections, send UDP packets, listen on TCP or UDP port,etc.
nc [options] [host] [port]
It is very easy to build basic client server model using this tool. To transfer file from one host to another,
On the host where you have the file (file.txt) to be transferred, run
$nc localhost 2000 <file.txt
On host where you want to get the file, run
$nc –l 2000 >file.txt
-l option instructs to listen on the specified port.
It is sometimes useful to talk to servers through command prompt. It helps in troubleshooting, to verify what data a server is sending in response to commands issued by the client. For example, to retrieve the home page of a web site:
$ echo -n “GET / HTTP/1.0\r\n\r\n” | nc http://www.yahoo.com 80
It will display the response sent by the web server. If we know the format of the requests required by the server, we can interactively send and get response using this tool.
It can also be used to do port scanning on any hosts. Port scanning is process of connecting to ports and reporting whether the service or server process is running or not.
$nc -z localhost 1-5000
Connection to localhost 22 port [tcp/ssh] succeeded!
Connection to localhost 25 port [tcp/smtp] succeeded!
Connection to localhost 111 port [tcp/sunrpc] succeeded!
Connection to localhost 631 port [tcp/ipp] succeeded!
Connection to localhost 1521 port [tcp/ncube-lm] succeeded!
Connection to localhost 3306 port [tcp/mysql] succeeded!
Another option that may come in handy is the -c option, which tells netcat to execute a command with /bin/sh after it connects — sending the output to the other side of the connection. This can be used on either side of the connection.
To send data from a command to a remote host, you could use
$netcat -c ‘/bin/command’ hostname port
When netcat connects to the service on the remote host, it will attempt to send the output of /bin/command
If you use netcat -l -p 1234 -c ‘/bin/command’, it will send the output of /bin/command to the first client that connects to port 1234, and then close the connection