Netcat Using Samples

How To Use Netcat for Port Scanning

One of the most common uses for netcat is as a port scanner.

Although netcat is probably not the most sophisticated tool for the job (nmap is a better choice in most cases), it can perform simple port scans to identify open ports easily.

We do this by specifying a range of ports to scan, as we did above, along with the -z option to perform a scan instead of attempting to initiate a connection.

For instance, we can scan all ports up to 1000 by issuing this command:

netcat -z -v 1-1000

Along with the -z option, we have also specified the -v option to tell netcat to provide more verbose information.

The output will look like this:

nc: connect to port 1 (tcp) failed: Connection refused
nc: connect to port 2 (tcp) failed: Connection refused
nc: connect to port 3 (tcp) failed: Connection refused
nc: connect to port 4 (tcp) failed: Connection refused
nc: connect to port 5 (tcp) failed: Connection refused
nc: connect to port 6 (tcp) failed: Connection refused
nc: connect to port 7 (tcp) failed: Connection refused
. . .
Connection to 22 port [tcp/ssh] succeeded!
. . .

As you can see, this provides a lot of information and will tell you for each port whether a scan was successful or not.

If you are actually using a domain name, this is the form you will have to use.

However, your scan will go much faster if you know the IP address that you need. You can then use the -n flag to specify that you do not need to resolve the IP address using DNS:

netcat -z -n -v 1-1000

The messages returned are actually sent to standard error (see our I/O redirection article for more info). We can send the standard error messages to standard out, which will allow us to filter the results easier.

We will redirect standard error to standard output using the 2>&1 bash syntax. We will then filter the results with grep:

netcat -z -n -v 1-1000 2>&1 | grep succeeded

Connection to 22 port [tcp/*] succeeded!

Here, we can see that the only port open in the range of 1-1000 on the remote computer is port 22, the traditional SSH port.

How To Communicate through Netcat

Netcat is not restricted to sending TCP and UDP packets. It also can listen on a port for connections and packets. This gives us the opportunity to connect two instances of netcat in a client-server relationship.

Which computer is the server and which is the client is only a relevant distinction during the initial configuration. After the connection is established, communication is exactly the same in both directions.

On one machine, you can tell netcat to listen to a specific port for connections. We can do this by providing the -l parameter and choosing a port:

netcat -l 4444

This will tell netcat to listen for TCP connections on port 4444. As a regular (non-root) user, you will not be able to open any ports under 1000, as a security measure.

On a second server, we can connect to the first machine on the port number we choose. We do this the same way we’ve been establishing connections previously:

netcat 4444

It will look as if nothing has happened. However, you can now send messages on either side of the connection and they will be seen on either end.

Type a message and press ENTER. It will appear on both the local and remote screen. This works in the opposite direction as well.

When you are finished passing messages, you can press CTRL-D to close the TCP connection.

How To Send Files through Netcat

Building off of the previous example, we can accomplish more useful tasks.

Because we are establishing a regular TCP connection, we can transmit just about any kind of information over that connection. It is not limited to chat messages that are typed in by a user. We can use this knowledge to turn netcat into a file transfer program.

Once again, we need to choose one end of the connection to listen for connections. However, instead of printing information onto the screen, as we did in the last example, we will place all of the information straight into a file:

netcat -l 4444 > received_file

On the second computer, create a simple text file by typing:

echo "Hello, this is a file" > original_file

We can now use this file as an input for the netcat connection we will establish to the listening computer. The file will be transmitted just as if we had typed it interactively:

netcat 4444 < original_file

We can see on the computer that was awaiting a connection, that we now have a new file called “received_file” with the contents of the file we typed on the other computer:

cat received_file
Hello, this is a file

As you can see, by piping things, we can easily take advantage of this connection to transfer all kinds of things.

For instance, we can transfer the contents of an entire directory by creating an unnamed tarball on-the-fly, transferring it to the remote system, and unpacking it into the remote directory.

On the receiving end, we can anticipate a file coming over that will need to be unzipped and extracted by typing:

netcat -l 4444 | tar xzvf -

The ending dash (-) means that tar will operate on standard input, which is being piped from netcat across the network when a connection is made.

On the side with the directory contents we want to transfer, we can pack them into a tarball and then send them to the remote computer through netcat:

tar -czf - * | netcat 4444

This time, the dash in the tar command means to tar and zip the contents of the current directory (as specified by the * wildcard), and write the result to standard output.

This is then written directly to the TCP connection, which is then received at the other end and decompressed into the current directory of the remote computer.

This is just one example of transferring more complex data from one computer to another. Another common idea is to use the dd command to image a disk on one side and transfer it to a remote computer. We won’t be covering this here though.

How To Use Netcat as a Simple Web Server

We’ve been configuring netcat to listen for connections in order to communicate and transfer files. We can use this same concept to operate netcat as a very simple web server. This can be useful for testing pages that you are creating.

First, let’s make a simple HTML file on one server:

nano index.html

Here is some simple HTML that you can use in your file:

                <title>Test Page</title>
                <h1>Level 1 header</h1>
                <p>Normal text here</p>

Save and close the file.

Without root privileges, you cannot serve this file on the default web port, port 80. We can choose port 8888 as a regular user.

If you just want to serve one page, one time to check how it renders, you can type something like this:

netcat -l 8888 < index.html

Now, in your browser, you can access the content by visiting:


netcat page served

This will serve the page, and then the netcat connection will close. If you attempt to refresh the page, it will be gone:

netcat page gone

We can have netcat serve the page indefinitely by wrapping the last command in an infinite loop, like this:

while true; do nc -l 8888 < index.html; done

This will allow it to continue to receive connections after the first connection closes.

We can stop the loop by typing CTRL-C on the server.

This allows you to see how a page renders in a browser, but it doesn’t provide much more functionality. You should never use this for serving actual websites. There is no security and simple things like links do not even work correctly.


One of the Linux command line tools I had initially under-estimated is netcat or just nc. By default, netcat creates a TCP socket either in listening mode (server socket) or a socket that is used in order to connect to a server (client mode). Actually, netcat does not care whether the socket is meant to be a server or a client. All it does is to take the data from stdin and transfer it to the other end across the network.

The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:

$ nc -l 3333

On the other end, connect to the server with the following:

$ nc 3333

In this case, the keyboard acts as the stdin. Anything you type in the server machine’s terminal is transfered to the client machine and vice-versa.

Transfering Files

In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with the following:

$ cat backup.iso | nc -l 3333

Receive backup.iso on the client machine with the following:

$ nc 3333 > backup.iso

As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing with large files. In such cases, a pipe-monitoring utility like pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered in real-time on the server side:

$ cat backup.iso | pv -b | nc -l 3333

Of course, the same can be implemented on the client side by piping netcat’s output through pv:

$ nc 3333 | pv -b > backup.iso

Other Examples

Netcat is extremely useful for creating a partition image and sending it to a remote machine on-the-fly:

$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333

On the remote machine, connect to the server and receive the partition image with the following command:

$ nc 3333 | pv -b > myhdb5partition.img.gz

This might not be as classy as the partition backups using partimage, but it is efficient.

Another useful thing is to compress the critical files on the server machine with tar and have them pulled by a remote machine:

$ tar -czf - /etc/ | nc -l 3333

As you can see, there is a dash in the tar options instead of a filename. This is because tar’s output needs to be passed to netcat.

On the remote machine, the backup is pulled in the same way as before:

$ nc 3333 | pv -b > mybackup.tar.gz


It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH tunnel.

Using an SSH tunnel has two advantages:

  1. The data is transfered inside an encrypted tunnel, so it is well-protected.
  2. You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections will take place through SSH.

You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs on this machine too.

$ cat backup.iso | nc -l 3333

On the client machine connect to the listening socket through an SSH tunnel:

$ ssh -f -L 23333: me@ sleep 10; \
        nc 23333 | pv -b > backup.iso

This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after file transfer finishes. For more information and explanation about it please read my article about auto-closing SSH tunnels.

Telnet-like Usage

Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word “server” from the “WordNet” database at the dictionary server, I’d do:

$ nc 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
     n 1: a person whose occupation is to serve at table (as in a
          restaurant) [syn: {waiter}]
     2: (court games) the player who serves to start a point
     3: (computer science) a computer that provides client stations
        with access to files and printers as shared resources to a
        computer network [syn: {host}]
     4: utensil used in serving food or drink
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]

Works as a Port Scanner too

A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just informs about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:

$ nc -z 80-90
Connection to 80 port [tcp/http] succeeded!

In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.

The man page contains some more interesting examples, so take the time to read it.









Leave a Reply

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

You are commenting using your 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