How To Use Netcat to Establish and Test TCP and UDP Connections | DigitalOcean (2024)

Introduction

Linux is known for having a great number of mature, useful command line utilities available out of the box in most distributions. Often, system administrators can do much of their work using the built-in tools without having to install additional software.

In this guide, we will discuss how to use the netcat utility. This versatile command can assist you in monitoring, testing, and sending data across network connections.

Netcat should be available on almost any modern Linux distribution. Ubuntu ships with the BSD variant of netcat, and this is what we will be using in this guide. Other versions may operate differently or provide other options.

General Syntax

By default, netcat operates by initiating a TCP connection to a remote host.

The most basic syntax is:

  1. netcat [options] host port

This will attempt to initiate a TCP connection to the defined host on the port number specified. This functions similarly to the old Linux telnet command. Keep in mind that your connection is entirely unencrypted.

If you would like to send a UDP packet instead of initiating a TCP connection, you can use the -u option:

  1. netcat -u host port

You can specify a range of ports by placing a dash between the first and last:

  1. netcat host startport-endport

This is generally used with some additional flags.

On most systems, we can use either netcat or nc interchangeably. They are aliases for the same command.

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 easily identify open ports.

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:

  1. netcat -z -v domain.com 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:

Output

nc: connect to domain.com port 1 (tcp) failed: Connection refusednc: connect to domain.com port 2 (tcp) failed: Connection refusednc: connect to domain.com port 3 (tcp) failed: Connection refusednc: connect to domain.com port 4 (tcp) failed: Connection refusednc: connect to domain.com port 5 (tcp) failed: Connection refusednc: connect to domain.com port 6 (tcp) failed: Connection refusednc: connect to domain.com port 7 (tcp) failed: Connection refused. . .Connection to domain.com 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:

  1. netcat -z -n -v 198.51.100.0 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:

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

Output

Connection to 198.51.100.0 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:

  1. 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 chose. We do this the same way we’ve been establishing connections previously:

  1. netcat domain.com 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:

  1. netcat -l 4444 > received_file

The > in this command redirects all the output of netcat into the specified filename.

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

  1. 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:

  1. netcat domain.com 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:

  1. cat received_file

Output

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:

  1. 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:

  1. tar -czf - * | netcat domain.com 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:

  1. nano index.html

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

index.html

<html> <head> <title>Test Page</title> </head> <body> <h1>Level 1 header</h1> <h2>Subheading</h2> <p>Normal text here</p> </body></html>

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 this page one time to check how it renders, you can run the following command:

  1. printf 'HTTP/1.1 200 OK\n\n%s' "$(cat index.html)" | netcat -l 8888

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

http://server_IP:8888

How To Use Netcat to Establish and Test TCP and UDP Connections | DigitalOcean (1)

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

How To Use Netcat to Establish and Test TCP and UDP Connections | DigitalOcean (2)

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

  1. while true; do printf 'HTTP/1.1 200 OK\n\n%s' "$(cat index.html)" | netcat -l 8888; 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.

Conclusion

You should now have a pretty good idea as to what netcat can be used for. It is a versatile tool that can be useful to diagnose problems and verify that base-level functionality is working correctly with TCP/UDP connections.

Using netcat, you can communicate between different computers very easily for quick interactions. Netcat attempts to make network interactions transparent between computers by taking the complexity out of forming connections.

How To Use Netcat to Establish and Test TCP and UDP Connections | DigitalOcean (2024)

FAQs

Can Netcat test UDP ports? ›

We can use the netcat/nc utility to test whether the LLT UDP ports are open for communication.

How to use Netcat to test TCP? ›

To test TCP connections with Netcat, follow these steps:
  1. Start Netcat in server mode listening on a specific port:
  2. 2.Start Netcat as a client establishing a connection to the server:
  3. 1.Start Netcat in server mode, listening on a specific port for UDP data:
  4. 2.Start Netcat as a client sending UDP data to the server:
Jul 18, 2023

Is Netcat default TCP or UDP? ›

By default Netcat uses the TCP protocol for its communications, but it can also UDP using the -u option. As we mentioned at the previous step, Netcat lets you convert your PC in a server. In this case we're going to establish the connection between the server and the client but using UDP.

How do I establish a connection using Netcat? ›

To get started, you need to enable the shell tool over a Netcat command by using Netcat reverse shell:
  1. nc -n -v -l -p 5555 -e /bin/bash. Then from any other system on the network, you can test how to run commands on host after successful Netcat connection in bash.
  2. nc -nv 127.0.0.1 5555. ...
  3. nc -n -v -l -p 5555 -e /bin/bash.

How can I test UDP connectivity? ›

iperf is a network throughput measurement tool that can test the throughput of either UDP or TCP. We can also use this tool to validate UDP connectivity. iperf works in a client-server setup. So, we need to establish both a client and a server to use it.

How to check if TCP and UDP ports are open? ›

How do I check if a UDP port is open in Windows? To view the TCP/UDP open port state of a remote host, type “portqry.exe –n [hostname/IP]” where [hostname/IP] is replaced with the hostname or IP address of the remote host.

How do I test TCP connection? ›

On a Windows computer

Press the Windows key + R, then type "cmd.exe" and click OK. Enter "telnet + IP address or hostname + port number" (e.g., telnet www.example.com 1723 or telnet 10.17.xxx.xxx 5000) to run the telnet command in Command Prompt and test the TCP port status.

How to send UDP packet with netcat? ›

Using Netcat to send a UDP packet without binding
  1. TYPE nc -ul -p 8899 Command in first Terminal.
  2. TYPE echo “Hello World” | nc -u -w1 127.0.0.1 8899 Command in the Second Terminal.
  3. In the first Terminal you can see the Packet is Successfully Received.
Dec 26, 2023

What is nc command for UDP? ›

Netcat (nc) Command Options
OptionTypeDescription
-U --unixsockProtocolUse Unix domain sockets.
-u --udpProtocolUse UDP connection.
-g <hop1, hop2,...>Connect modeSet hops for loose source routing in IPv4. Hops are IP addresses or hostnames.
-p <port> --source-port <port>Connect modeBinds the Netcat source port to <port>.
7 more rows
May 24, 2022

How to establish TCP connection in Linux? ›

Establishing a TCP connection on Linux
  1. Edit the file /etc/services. ...
  2. Edit the file /etc/inetd.conf. ...
  3. Find the process ID of the inetd with the command: ps -ef | grep inetd.
  4. Run the command: kill -1 inetd processid.

Can telnet test UDP port? ›

Telnet is a built-in command in Windows and Linux systems. Third-party telnet clients are also available. You can use Telnet to check for TCP ports. It cannot check UDP ports.

How long is Netcat UDP? ›

netcat uses 1024 bytes in UDP mode.

How do I establish network connections? ›

  1. Step 1: Connect your router to your modem. Don't plug your router into the power outlet just yet. ...
  2. Step 2: Connect your router to your computer. Connect a computer manually to the router using an Ethernet cable. ...
  3. Step 3: Create a username and password, or find the existing one. ...
  4. Step 3: Continue setting up your router.

How to use ncat command? ›

ncat -l [ <host> ] [ <port> ]

In listen mode, <host> controls the address on which Ncat listens; if you omit it, Ncat will bind to all local interfaces (INADDR_ANY). If the port number is omitted, Ncat uses its default port 31337. Typically only privileged (root) users may bind to a port number lower than 1024.

How to connect UDP port? ›

Opening TCP/UDP port
  1. Locate your router's IP address.
  2. Head over to your router's settings.
  3. Enter your credentials (username and password).
  4. Look around for the Port Forwarding tab.
  5. Open your preferred port—for example, type 8080 to open port 8080.
  6. Save your settings.
Jan 14, 2021

Can netcat send UDP packets? ›

Netcat can be used to send UDP packets with the -u option. With UDP you don't need to bind to a local port, you can send one-off packets. Specify the target IP and port and any data will be sent as a UDP packet.

How do I monitor UDP traffic on my network? ›

To monitor TCP and UDP traffic, you need to use tools that can capture and analyze the packets that are sent and received over the network. Some of the common tools are Wireshark, tcpdump, nmap, netstat, and iperf.

Can Telnet test UDP ports? ›

Powershell, PUTTY, and Telnet can only test TCP ports.

How to check UDP ports in Linux? ›

Use ss command to display all open TCP and UDP ports in Linux. Another option is to use the netstat command to list all ports in Linux. Apart from ss / netstat one can use the lsof command to list open files and ports on Linux based system. Finally, one can use nmap command to check TCP and UDP ports too.

References

Top Articles
D’Vontaye Mitchell, who died after being pinned to the ground in Milwaukee, died from asphyxia and drugs, autopsy report says | CNN
Egypt: New law threatens to reduce access to healthcare for millions
Wordscapes Level 5130 Answers
Myexperience Login Northwell
Stadium Seats Near Me
Craigslist Portales
Teenbeautyfitness
How Much Is 10000 Nickels
Zitobox 5000 Free Coins 2023
Slay The Spire Red Mask
Valentina Gonzalez Leaked Videos And Images - EroThots
Tripadvisor Near Me
Myql Loan Login
2021 Lexus IS for sale - Richardson, TX - craigslist
Programmieren (kinder)leicht gemacht – mit Scratch! - fobizz
Craigslist Pikeville Tn
Marion County Wv Tax Maps
Northern Whooping Crane Festival highlights conservation and collaboration in Fort Smith, N.W.T. | CBC News
Les Rainwater Auto Sales
Idaho Harvest Statistics
Walmart stores in 6 states no longer provide single-use bags at checkout: Which states are next?
Wausau Obits Legacy
Forum Phun Extra
Where Is The Nearest Popeyes
[Cheryll Glotfelty, Harold Fromm] The Ecocriticism(z-lib.org)
Chase Bank Pensacola Fl
Dcf Training Number
Certain Red Dye Nyt Crossword
Obituaries Milwaukee Journal Sentinel
Delectable Birthday Dyes
Harrison County Wv Arrests This Week
What Sells at Flea Markets: 20 Profitable Items
ATM, 3813 N Woodlawn Blvd, Wichita, KS 67220, US - MapQuest
100 Million Naira In Dollars
25Cc To Tbsp
Litter-Robot 3 Pinch Contact & DFI Kit
Car Crash On 5 Freeway Today
Maybe Meant To Be Chapter 43
2 Pm Cdt
Henry Ford’s Greatest Achievements and Inventions - World History Edu
Silive Obituary
Emulating Web Browser in a Dedicated Intermediary Box
The Conners Season 5 Wiki
3 bis 4 Saison-Schlafsack - hier online kaufen bei Outwell
2Nd Corinthians 5 Nlt
Meet Robert Oppenheimer, the destroyer of worlds
855-539-4712
Hughie Francis Foley – Marinermath
Pronósticos Gulfstream Park Nicoletti
Psalm 46 New International Version
San Pedro Sula To Miami Google Flights
Volstate Portal
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 6105

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.