8 Ways to use the (Netcat) nc Command in Linux

nc Command

The nc (Netcat) is a command-line utility that uses TCP or UDP protocols to read and write data across network connections. It is considered the Swiss Army knife of networking tools because of its versatile applications.

netcat is cross-platform and is available for Linux, macOS, Windows, and BSD platforms. You can use it for various tasks, including data transfer, port scanning, debugging, monitoring network connections, and proxy servers.

The netcat package comes pre-installed on macOS and well-known Linux distributions, like Ubuntu, Debian, and CentOS.

In this detailed guide, we’ll start with a comprehensive introduction to the nc utility. We’ll then discuss 8 practical applications of the utility. Finally, we’ll end with a short discussion on how to use netcat safely on your system.

Table of Contents

  1. Basic nc Command Syntax
    1. Two Modes of Netcat Operation
    2. The nc Command Options
  2. 8 Practical Usages of the nc Utility
    1. Prerequisites
    2. Use Case #1: Set Up a Client/Server Connection
    3. Use Case #2: Ping a Website’s Specific Port
    4. Use Case #3: Scan for Open Ports
    5. Use Case #4: Transfer Files
    6. Use Case #5: Transfer Directory
    7. Use Case #6: Create a Basic Web Server
    8. Use Case #7: Create a Simple Chat Server
    9. Use Case #8: Sending HTTP Requests
  3. Is netcat a Security Risk?
  4. Conclusion
  5. FAQs

Basic nc Command Syntax

The basic syntax of the nc command is as follows:

# nc [<options>] <host> <port>

This syntax of nc command is made up of the following parts:

  • In Ubuntu, the nc and netcat commands serve as symbolic links to the OpenBSD version of the netcat utility. In contrast, on Debian, RHEL, and CentOS systems, the corresponding command is ncat.
  • <host> represents a symbolic hostname or a numeric IP address.
  • Similarly, <port> refers to a service name or a port number, providing flexibility in specifying the target host and port for network connections.

Two Modes of Netcat Operation

The netcat utility operates in two modes: connect mode and listen mode. Let’s discuss these modes in detail.

The Connect Mode

netcat acts as a client in the Connect mode. The utility requires the parameters <host> and <port>. The Connect mode is used in scenarios where you want to establish a connection with another system or network.

The Listen Mode

In the Listen mode, netcat operates as a server and “listens” for incoming connections. In this mode, netcat waits for connection requests on a specified port. If you omit the <host> parameter when using netcat in the listen mode, it automatically listens on all available network addresses for the specified port.

Without any options, the command tries to establish a TCP connection at the host and port you added as arguments.

The nc Command Options

The nc Command Options

Now that you know the basic syntax and operational modes, let’s see the following table that lists the popular options for this utility:

Note that this is not a complete list, and we recommend using the man command to access the utility’s manual page:

# man netcat

Use the arrow keys to navigate the information and q to quit.

8 Practical Usages of the nc Utility

Thanks to the flexibility of the netcat utility, you can use it for surprisingly different use cases. Let’s look at the eight practical uses of the utility. Let’s see the prerequisites for trying out these use cases.

Prerequisites

You’ll need two devices connected to the same network. We recommend trying out these examples with two Ubuntu virtual machines. Ensure you can access both devices and know their IP addresses (you can find this information using the ifconfig command in the terminal of each machine).

IP Address for System/Device 1

IP Address for SystemDevice 1

IP Address for System/Device 2

IP Address for SystemDevice 2

Use Case #1: Set Up a Client/Server Connection

In this scenario, the two devices are connected via a primary client/server connection. In this setup, one device acts as a server and listens for incoming connections while the other tries to find and connect to the server.

Start by using the nc utility in the Listen mode on the first device. Remember to provide an open port as the argument:

# nc -lv <port>

# nc -lv port nc command

In the above command, the -l flag enabled the Listen mode, and the -v flag indicates that the device is listening for connections.

Next, on the second device, launch the nc utility with the -v flag, and enter the IP address and the open port on the first device:

# nc -v System IP 1234

# nc -v System IP 1234 nc command

The client will use the IP and port information to successfully set up a client/server connection.

Now, when a message is sent from one device to another, it appears on both devices. To terminate the connection, hit CTRL+C on any device.

Use Case #2: Ping a Website’s Specific Port

You can use the netcat utility to test a specific port on a website instead of the more limited ping command.

For instance:

# nc -zv redswitches.com 443

# nc -zv redswitches.com 443 nc command

The output displays the message “successful connection” if the ping is successful. The -z flag makes sure that the connection terminates successfully.

Use Case #3: Scan for Open Ports

You can use the nc utility to find open ports.

Start by running the following command on the second device. This will set up the utility on the device in the Listen mode at port 1234:

# nc -lkv 23

# nc -lkv 23 nc command

The -k flag ensures the connection remains open after the initial disconnect. Now, run the following command on the second device to check if port 23 is open.

# nc -zv System_ip 23

# nc -zv System_ip 23 nc command

The output displays a successful connection message if the port is open.

Alternatively, you can add a port range to the second device and use it to scan multiple ports.

For example:

# nc -zv system IP 19-25

# nc -zv system IP 19-25 nc command

For every port, the output indicates whether the connection was successful. If you supplied a large number of ports, we suggest using the grep utility to filter the results.

number of ports nc command

For instance, grepping for the word ‘succeeded’ only returns open ports in the output.

Use Case #4: Transfer Files

You can use the netcat utility to transfer files using the connection between the devices. Follow these easy steps to see how these file transfers work.:

On the first device, use the touch command to create a sample file:

# touch rstestfile.txt

Now, set up the netcat utility in the Listen mode and redirect the sample file to the utility. For this, use the following command:

# nc -lv 23 < rstestfile.txt

Now, send the file to the second device by connecting to it and sending redirecting the file:

# nc -zv 184.107.122.43 23 > rstestfile.txt

# nc -zv 184.107.122.43 23 rstestfile.txt

Use the ls command to confirm that the file transfer is finished.

Use Case #5: Transfer Directory

The process of transferring directories is not as straightforward as the file transfer. If you wish to send multiple files and directories, we suggest compressing all files and directories in an archive and then redirecting the archive to the other device. We recommend the tar command for creating the archive.

Before starting the utility, create a directory on both devices and add some files. For this, run the following command on both devices:

# mkdir files; touch files/file{1..5}.txt

Use the cd command to navigate to the directory:

# cd files

Establish and share the destination directory on the other device.

# mkdir files_destination && cd files_destination

Set up a port 23 listening connection using the netcat utility and send the tar command through it:

# nc -lv 23 | tar xfv -

Next, send the tar archive to the second device.

# tar -cf - . | nc -v system ip port

# tar -cf - . nc -v system ip port

Use Case #6: Create a Basic Web Server

You can use netcat to set up a simple web server on a device.

For this, launch the utility with the -l flag to set up a simple but non-secure web server. We strongly discourage using this server for anything other than educational purposes.

Start by creating an a.html file using your preferred editor on the device:

$ vim index.html

Next, add the following lines in the file.

<html>

<head>

<title>Test Page</title>

</head>

<body>

<p>Serving this file using Netcat Basic HTTP server!</p>

</body>

</html>

Use Case #6 Create a Basic Web Server

Save and close the file.

Next, use the following command to serve the a.html file over HTTP until you take down the server. For this, run the following command in the terminal:

$ while : ; do ( echo -ne "HTTP/1.1 200 OK\r\n" ; cat index.html; ) | nc -l -p 8080 ; done

$ while ; do ( echo -ne HTTP1.1 200 OKrn ; cat index.html; ) nc -l -p 8080 ; done

Use Case #7: Create a Simple Chat Server

You can create a simple chat server using the netcat’s communication feature.

On one device, execute the following command to set up the server with interactive capabilities:

awk -W interactive '$0="Charlie: "$0' | nc -lv 1234

In the above command, `Charlie` is the username for the server.

On another device, run the same command but give it a new username (we used Eve) and connect to the chat server:

awk -W interactive '$0="Eve: "$0' | nc 10.0.2.4 1234

Now, you can exchange messages between Charlie (device 1) and Eve (device 2). They’ll see messages from each other with their respective names, but their usernames won’t clutter their chat windows.

Use Case #8: Sending HTTP Requests

You can combine netcat with printf to send an HTTP request to a website. For instance, use this command to send a request to ‘example.com’ on port 80 for a TCP/IP connection:

# printf "GET / HTTP/1.0\r\n\r\n" | nc -v example.com 80

This command will display the page header and contents in the terminal.

Note: This command might not work in some cases because most websites usually block these requests, and you may see a 404 error page.

Is netcat a Security Risk?

netcat can pose security risks if misused. Although it is a widely used and versatile networking tool for authorized purposes in network administration, it can also be exploited for malicious activities.

Like all popular utilities, it is easy to misuse netcat for activities like unauthorized access, spying, exploiting vulnerabilities, bypassing firewalls, and creating backdoors. Some specific netcat options, such as ‘-e’ and ‘-d,’ are commonly used in malicious scripts to execute harmful commands on remote computers.

It’s essential to download Netcat from trusted sources and carefully evaluate its use options, especially on frontend systems. It’s important to note that netcat transmits data without encryption, making it unsuitable for insecure networks. We recommend safer alternatives like Cryptcat or SSH tunneling for secure data transfers over the internet.

While netcat has advantages, users, system administrators, and IT managers should use it carefully. Newer tools like Socat offer more features and security enhancements.

Despite its age, netcat remains popular due to its simplicity and ease of use. Security professionals often combine it with utilities like netsh for efficient network diagnostics and management.

Conclusion

The netcat or the nc, is a highly adaptable utility with multiple applications. This guide has illustrated how to use it through various examples, demonstrating its capacity to create connections, transfer data, and function as an easy-to-use yet powerful network tool.

For network enthusiasts and administrators alike, it is an excellent source for debugging, port scanning, and establishing connections. It is a vital part of any network toolkit due to its simple syntax and extensive functionality. Users can leverage netcat’s capabilities to improve their network-related tasks and troubleshooting endeavors by using the knowledge they acquire from this guide.

RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is the nc command, and what is its primary purpose?

The nc (Netcat) command is a widely used utility for handling network connections. Its primary purpose is to establish and manage network connections.

Q. How can I use nc for basic connectivity testing?

You can employ the nc command for straightforward connectivity tests. To check if a remote server has an open port, execute this: # nc -zv <hostname> <port>.

Q. Can nc be used for file transfer?

Certainly, nc is a handy tool for file transfers. For instance, it allows you to send a file from one host to another using a command like: # nc -l <port> > received_file.

Q. What is the significance of the -l option in nc?

The -l option in nc stands for “listen mode,” enabling hosts to accept incoming connections. It’s commonly used alongside other options to create a listening server.

Q. How does nc facilitate port scanning?

Port scanning with nc involves the detection of open ports on a target system. You can perform this task by utilizing a command like # nc -zv <hostname> <start_port-end_port> to scan a range of ports.

Q. Can nc be used for chat-like communication between two hosts?

You can set up nc to create a two-way chat environment between two hosts. To establish a simple chat connection, run # nc -l <port> on one host and # nc <hostname> <port> on the other.

Q. Is nc suitable for serving as a simple web server?

Indeed, nc can serve as a basic web server. For instance, you can set up a minimal HTTP server that serves the content of index.html with the command # nc -l -p <port> -q 1 < index.html.

Q. How does nc contribute to troubleshooting network issues?

nc assists in network troubleshooting by enabling users to test connectivity, verify open ports, and execute various network-related tasks, providing valuable insights into potential problems.

Q. Can nc be used in scripts for automation?

nc is script-friendly and seamlessly integrates into scripts to automate various network-related tasks.

Q. Is nc suitable for both TCP and UDP connections?

Yes, nc supports both TCP and UDP connections. Users can specify the protocol using options such as -u for UDP or omitting it for TCP connections.

Q. What does Netcat’s verbose output, enabled with “-v,” signify, and why is it valuable in network operations?

Verbose output in Netcat provides detailed network connection and data transfer information. It’s crucial for debugging and comprehending communication processes between machines. Network operators use it to troubleshoot issues and monitor network activities, gaining valuable insights.

Q. How does Netcat’s port scanning feature, achieved with “-zv,” empower network administrators and security experts?

Using the -zv option, Netcat’s port scanning is a potent tool for network administrators and security experts. It swiftly identifies open ports on target machines, aiding network security assessment and vulnerability detection. It ensures that only necessary ports are accessible, strengthening the network’s security.