How To Check Tcp Connection In Linux : Linux TCP Connection Monitoring

Monitoring active TCP connections on your Linux machine helps you see exactly what services are communicating. Knowing how to check tcp connection in linux is essential for troubleshooting network issues, identifying unauthorized access, and optimizing system performance. This guide walks you through the most effective commands and tools, from simple built-in utilities to advanced monitoring techniques.

Whether you’re a system administrator or a curious developer, understanding TCP connections gives you control over your network traffic. You’ll learn to spot suspicious activity, verify that services are running correctly, and diagnose connectivity problems quickly.

Why Check TCP Connections In Linux

TCP connections form the backbone of most network communication on Linux. Every time you browse a website, send an email, or connect to a database, TCP ensures reliable data transfer. Checking these connections helps you:

  • Identify which services are listening for incoming connections
  • Detect unauthorized remote access attempts
  • Monitor bandwidth usage per connection
  • Troubleshoot slow or failed connections
  • Verify firewall rules are working as expected

Without regular checks, you might miss performance bottlenecks or security threats. Let’s explore the most common methods.

How To Check Tcp Connection In Linux

The ss command is the modern replacement for netstat. It’s faster and provides more detailed information. Most Linux distributions include it by default.

Using The Ss Command For TCP Connections

Open your terminal and type:

ss -t

This shows all TCP sockets. The -t flag filters for TCP only. You’ll see output like:

State      Recv-Q Send-Q        Local Address:Port          Peer Address:Port
ESTAB      0      0            192.168.1.10:ssh            192.168.1.5:54321
LISTEN     0      128                 0.0.0.0:http               0.0.0.0:*

For more detail, add the -a flag to show all sockets (listening and established):

ss -ta

To see numeric addresses instead of hostnames, use -n:

ss -tan

This is often faster and avoids DNS lookups. The -p flag shows which process owns each connection:

ss -tunap

Here, -u includes UDP, -n shows numbers, -a shows all, and -p shows process info. You’ll see PID and program name for each connection.

Filtering TCP Connections With Ss

You can filter by state, port, or address. For example, to see only established connections:

ss -t state established

To see connections on a specific port (like port 80):

ss -t sport = :80

Or for destination port:

ss -t dport = :443

Combine filters for precise results. This is useful when troubleshooting a specific service.

Using Netstat For TCP Connection Checking

While ss is preferred, netstat is still widely used. It’s part of the net-tools package. Install it if missing:

sudo apt install net-tools   # Debian/Ubuntu
sudo yum install net-tools   # RHEL/CentOS

Basic command to show TCP connections:

netstat -t

Add -a for all sockets:

netstat -ta

Show numeric addresses and process info:

netstat -tanp

Netstat output is similar to ss but slightly slower on busy systems. Still, it’s a reliable fallback.

Common Netstat Flags For TCP

  • -t: TCP connections only
  • -u: UDP connections
  • -l: Listening sockets only
  • -p: Show process ID and name
  • -n: Numeric output (no DNS)
  • -r: Show routing table

Example to see only listening TCP ports:

netstat -tln

This is great for checking which services are waiting for connections.

Checking TCP Connections With Lsof

The lsof command lists open files, and on Linux, network connections are treated as files. It’s useful for seeing which process uses a specific port.

Install if needed:

sudo apt install lsof

To list all TCP connections:

lsof -i TCP

To see connections on a specific port:

lsof -i :22

This shows the process name and PID using port 22 (SSH). Combine with -P for port numbers instead of service names:

lsof -i TCP -P

Lsof is particularly helpful when you need to kill a process that’s holding a port.

Using The Proc Filesystem For TCP Details

Linux exposes TCP connection data in the /proc filesystem. This is the raw data that tools like ss and netstat read.

Check the file:

cat /proc/net/tcp

Output shows hex-encoded addresses and ports. For IPv6, check:

cat /proc/net/tcp6

Decode the hex: the local address 0100007F:0035 means 127.0.0.1:53. This method is low-level but useful for scripting or when other tools aren’t available.

Parsing Proc TCP Data With Awk

You can extract meaningful info with a simple script:

awk '{print $2, $3, $4}' /proc/net/tcp | head -10

This shows local address, remote address, and connection state. State codes: 01 = ESTABLISHED, 02 = SYN_SENT, 03 = SYN_RECV, 04 = FIN_WAIT1, 05 = FIN_WAIT2, 06 = TIME_WAIT, 07 = CLOSE, 08 = CLOSE_WAIT, 09 = LAST_ACK, 0A = LISTEN, 0B = CLOSING.

Real-Time TCP Connection Monitoring

For live monitoring, use watch with ss or netstat. This updates every 2 seconds:

watch -n 2 ss -tan

Or with netstat:

watch -n 2 netstat -tan

For more advanced real-time monitoring, consider iftop or nethogs. Install them:

sudo apt install iftop nethogs

Run iftop to see bandwidth usage per connection:

sudo iftop

Run nethogs to see per-process bandwidth:

sudo nethogs

These tools give you a dynamic view of TCP traffic.

Understanding TCP Connection States

When checking TCP connections, you’ll see various states. Here’s what they mean:

  • LISTEN: The socket is waiting for incoming connections
  • ESTABLISHED: Active connection between two hosts
  • TIME_WAIT: Connection closed, waiting for packets to expire
  • CLOSE_WAIT: Remote side closed, local side hasn’t closed yet
  • FIN_WAIT1/2: Connection is being closed
  • SYN_SENT: Attempting to establish a connection

Many connections in TIME_WAIT are normal. But too many CLOSE_WAIT connections might indicate a bug in your application.

Checking TCP Connections For Specific Services

To check connections for a specific service, combine commands with grep. For example, check SSH connections:

ss -tan | grep :22

Or for HTTP:

ss -tan | grep :80

You can also filter by process name using ss -p:

ss -tanp | grep nginx

This shows all TCP connections owned by nginx processes.

Counting Active Connections

Count established connections:

ss -tan state established | wc -l

Count connections per state:

ss -tan | awk '{print $1}' | sort | uniq -c

This gives you a quick overview of connection health.

Using Tcpdump For Deep Packet Inspection

When you need to see the actual packets, tcpdump is your tool. It captures network traffic for analysis.

Install:

sudo apt install tcpdump

Capture TCP traffic on interface eth0:

sudo tcpdump -i eth0 tcp

Capture traffic for a specific port:

sudo tcpdump -i eth0 port 80

Save capture to a file for later analysis:

sudo tcpdump -i eth0 -w capture.pcap tcp

Read the file:

tcpdump -r capture.pcap

Tcpdump is powerful but requires root privileges. Use it when you need to see the full packet contents.

Checking TCP Connections With Nmap

Nmap is a network scanner that can check TCP connections from a remote perspective. It’s useful for testing what ports are open on your machine.

Install:

sudo apt install nmap

Scan your own machine:

nmap 127.0.0.1

Scan a remote host:

nmap 192.168.1.1

Use -sT for TCP connect scan:

nmap -sT 192.168.1.1

This completes a full TCP handshake. Nmap shows open ports and service names.

Automating TCP Connection Checks

You can script TCP connection checks for regular monitoring. Here’s a simple bash script:

#!/bin/bash
echo "TCP Connection Report - $(date)"
echo "================================"
echo "Listening ports:"
ss -tln | awk '{print $4}'
echo ""
echo "Established connections:"
ss -tan state established | wc -l
echo ""
echo "Top 5 remote IPs:"
ss -tan state established | awk '{print $5}' | sort | uniq -c | sort -rn | head -5

Save as tcp_check.sh, make executable, and run periodically with cron.

Troubleshooting Common TCP Issues

When you check TCP connections, you might find problems. Here are common issues and fixes:

Too Many TIME_WAIT Connections

Thousands of TIME_WAIT connections can exhaust resources. Check with:

ss -tan state time-wait | wc -l

If excessive, adjust kernel parameters:

sudo sysctl -w net.ipv4.tcp_fin_timeout=30

Or enable reuse:

sudo sysctl -w net.ipv4.tcp_tw_reuse=1

Connection Refused Errors

If you see SYN_SENT but no ESTABLISHED, the remote side might not be listening. Check:

ss -tan state syn-sent

Verify the service is running on the remote host.

High Number Of CLOSE_WAIT Connections

This indicates the application isn’t closing sockets properly. Find the process:

ss -tanp state close-wait

Then restart or fix the application.

Security Implications Of TCP Connection Monitoring

Regularly checking TCP connections helps detect intrusions. Look for:

  • Unexpected listening ports
  • Connections to unknown IP addresses
  • Multiple connections from the same remote IP
  • Connections on non-standard ports

Use ss -tanp to see which processes own each connection. If you see a suspicious process, investigate immediately.

Comparing Tools For Checking TCP Connections

Here’s a quick comparison:

Tool Speed Detail Real-time Best For
ss Fast High No General use
netstat Medium High No Legacy systems
lsof Medium Very high No Process-to-port mapping
tcpdump Slow Full packet Yes Deep analysis
iftop Fast Bandwidth Yes Bandwidth monitoring

Choose based on your specific need. For quick checks, ss is usually best.

Practical Example: Diagnosing A Slow Web Server

Let’s walk through a real scenario. Your web server is slow. Check TCP connections:

  1. Run ss -tan | grep :80 to see HTTP connections
  2. Look for many SYN_RECV connections, which might indicate a SYN flood
  3. Check ss -tan state time-wait | wc -l for excessive TIME_WAIT
  4. Use ss -tanp | grep apache to see Apache’s connections
  5. Run iftop to see bandwidth usage per connection

If you see many SYN_RECV, consider enabling SYN cookies:

sudo sysctl -w net.ipv4.tcp_syncookies=1

If TIME_WAIT is high, adjust kernel parameters as mentioned earlier.

Advanced: Using Bpftrace For TCP Monitoring

For deep kernel-level monitoring, bpftrace can trace TCP events. Install:

sudo apt install bpftrace

Trace TCP connect calls:

sudo bpftrace -e 'kprobe:tcp_connect { printf("Connect: %s:%d -> %s:%d\n", ntop2(ntop(4, arg1)), ntop2(ntop