Here is a quick tutorial on simulating UDP and TCP connections on Linux terminal using Netcat (NCat). Netcat package comes bundled with the famous Linux port scanning tool: NMap.

Setup

  • Get Netcat by installing NMap.
// for RHEL/CentOS
$ sudo yum install nmap -y

// for Ubuntu/Debian
$ sudo apt-get update
$ sudo apt-get install nmap -y
  • Next, you can setup one Netcat instance to listen to a certain port either via TCP/UDP transport protocol and setup another Netcat instance to establish a connection to it. Once the connection is established, both instances can send messages to other instances, which will work like a simple chat server and client.

Netcat options

  • -l: set to listening state which create a simple HTTP server waiting for the incoming connections
  • -p: define local port
  • -u: set the UDP mode

UDP

  • Create a UDP server listening on 30000 port.
$ nc -u -l 30000
  • On a new terminal tab, run below command to create an instant UDP client communicating with the above server. You can input any simple text, click enter, and see it appearing in the server’s output stream.
$ nc -u localhost 30000

Hello world from client!  <--- this appears in server's output stream too.

TCP

  • Create a TCP server listening on 31000 port.
$ nc -l 31000
  • On a new terminal tab, run below command to create an instant TCP client communicating with the above server. You can input any simple text, click enter, and see it appearing in the server’s output stream.
$ nc localhost 31000

Hello world from client!  <--- this appears in server's output stream too.

Verify

  • Run netstat to verify the established connections.
// TCP
$ netstat -nat | grep 31000

// UDP
$ netstat -nau | grep 30000

Netstat options

  • -v: enable verbose logs
  • -n: show numeric host, port or user names
  • -a: show both listening and non-listening (for TCP this means established connections) sockets

✅ Tested OS's : RHEL 7+, CentOS 7+, Ubuntu 18.04+, Debian 8+
✅ Tested Gear : Cloud (AWS EC2), On-Prem (Bare Metal)

Leave a comment