The Ultimate Guide to Linux Networking Commands

admin
admin

Mastering Linux networking commands is essential for system administrators, DevOps engineers, and cybersecurity professionals. This guide covers every critical command, from basic connectivity checks to advanced packet analysis, with practical examples and real-world applications.

Essential Connectivity Commands

ping – Basic Network Reachability

The ping command sends ICMP Echo Request packets to verify host reachability. Use ping -c 5 8.8.8.8 to limit probes to five packets. The -i flag sets interval (e.g., -i 0.5 for half-second). For IPv6, use ping6 or ping -6. Interpret output fields: ttl (time-to-live) indicates hops remaining; time shows round-trip latency. Packet loss >1% suggests network congestion. On modern systems, ping uses ICMP sockets, requiring root for certain options like -f (flood mode) used in stress testing.

traceroute / traceroute6 – Path Discovery

Traceroute maps the route packets take to a destination. It increments TTL values, causing intermediate routers to return ICMP Time Exceeded messages. Use traceroute -n google.com to skip DNS resolution for faster results. The -I flag uses ICMP probes instead of UDP (default), which bypasses firewalls blocking UDP. Three probes per hop show latency variation. Asterisks (* * *) indicate no response, often due to firewall filtering. IPv6 counterpart traceroute6 works identically.

mtr – Combined Ping and Traceroute

The mtr command (My TraceRoute) continuously probes each hop, displaying live statistics. Run mtr -r -c 10 example.com for a report mode with 10 packets per hop. Columns show: Loss%, Snt (sent), Last, Avg, Best, Wrst, and StDev. This tool excels at identifying intermittent packet loss on specific hops. Install with sudo apt install mtr (Debian/Ubuntu) or sudo yum install mtr (RHEL/CentOS).

Network Interface Configuration

ip – Modern Swiss Army Knife

The ip command replaces legacy ifconfig, route, and arp. Syntax: ip [OPTIONS] OBJECT {COMMAND}. Key objects: addr, link, route, neigh.

IP Address Management:

  • ip addr show – list all interfaces with IPv4/IPv6 addresses
  • ip addr add 192.168.1.10/24 dev eth0 – assign address
  • ip addr del 192.168.1.10/24 dev eth0 – remove address

Interface Control:

  • ip link set eth0 up/down – enable/disable interface
  • ip link set eth0 mtu 1500 – set maximum transmission unit
  • ip link set eth0 promisc on – enable promiscuous mode (for packet sniffing)

Routing Table:

  • ip route show – display routing table
  • ip route add default via 192.168.1.1 – set default gateway
  • ip route add 10.0.0.0/8 via 192.168.1.254 dev eth0 – add static route

ARP Cache:

  • ip neigh show – display neighbor table (ARP cache)
  • ip neigh del 192.168.1.5 dev eth0 – flush specific entry

ifconfig – Legacy Interface Configuration (Deprecated)

Though superseded by ip, ifconfig remains prevalent. Usage: ifconfig eth0 192.168.1.10 netmask 255.255.255.0 up. It shows MAC address, RX/TX packets, errors, drops, and collisions. Note: Modern distributions may require sudo apt install net-tools to obtain this command.

ethtool – NIC Driver and Hardware Settings

ethtool eth0 displays supported speeds, advertised link modes, and driver information. Critical flags: ethtool -s eth0 speed 1000 duplex full autoneg on forces gigabit full-duplex. Use ethtool -S eth0 for detailed statistics (CRC errors, collisions, timeouts). The -k flag shows offload features (checksum offloading, TCP segmentation offload). Diagnose physical issues with ethtool -p eth0 to blink the NIC LED for identification.

nmtui / nmcli – NetworkManager Control

For systems using NetworkManager (common in desktop environments), nmtui provides a text-based interface to manage connections. For scripting, nmcli dev status lists devices; nmcli con up/down MyConnection controls connections. nmcli dev wifi list scans wireless networks.

DNS and Name Resolution

nslookup – Legacy DNS Query

Interactive or single-query mode: nslookup example.com. For specific record types, use set type=MX then query. Use nslookup example.com 8.8.8.8 to query a specific resolver. Output shows canonical name (if alias), IP addresses, and authoritative servers.

dig – Advanced DNS Troubleshooting

The Domain Information Groper is the most flexible DNS tool. Syntax: dig @server name record_type. Common examples:

  • dig example.com ANY +noall +answer – show all records
  • dig -x 8.8.8.8 – reverse DNS lookup
  • dig example.com MX +short – just mail exchanger values
  • dig +trace example.com – simulate recursive resolution from root servers

Use +tcp to force TCP transport (bypasses UDP limits). The +dnssec flag checks DNSSEC validation. Query time in ms appears in footer.

host – Simplified DNS Lookup

host example.com returns A, AAAA, and MX records. host -t CNAME www.example.com checks specific record. host -l domain.com ns1.isp.com attempts zone transfer (usually blocked). Faster than dig for simple checks, but less control over output.

resolvectl – Systemd-Resolved Management

On systems using systemd-resolved, resolvectl status shows current DNS servers per interface. resolvectl query example.com performs local DNS resolution. resolvectl dns eth0 8.8.8.8 sets per-interface DNS. resolvectl flush-caches clears cached records.

Connection and Socket Analysis

netstat – Network Statistics (Deprecated)

Legacy tool, but widely found. Options: netstat -tulpn shows all listening TCP/UDP ports with process names. netstat -an displays all connections (established, listening, time-wait). netstat -i shows packet statistics per interface. netstat -r displays routing table. Note security: -p requires root to show process information.

ss – Modern Socket Statistics (Preferred)

The ss command is faster and more feature-rich than netstat. Key syntax:

  • ss -tulpn – listening TCP/UDP sockets
  • ss -state established – only established connections
  • ss -s – socket summary statistics
  • ss -i – internal TCP info (cwnd, ssthresh, rtt)
  • ss dst 192.168.1.1 – filter by destination

For debugging performance: ss -ti shows TCP timestamps, window scale, and selective ACK (sack). The -m flag provides memory usage per socket.

lsof – List Open Files (Network Focus)

lsof -i shows all network connections. lsof -i :80 filters by port. lsof -iTCP -sTCP:LISTEN shows only listening TCP services. lsof -i @192.168.1.1 filters by IP. Use lsof -P -n -i to disable DNS and port name resolution for speed. Identify which process holds a port: lsof -i :443.

Packet Capture and Traffic Analysis

tcpdump – Command-Line Packet Analyzer

Powerful packet capture with Berkeley Packet Filter (BPF) syntax.
Fundamental examples:

  • tcpdump -i eth0 – capture all traffic on interface
  • tcpdump -i any port 80 – HTTP traffic
  • tcpdump -nn -X -c 10 – don’t resolve names, print hex/ASCII, stop after 10 packets
  • tcpdump -w capture.pcap – write to file for Wireshark
  • tcpdump -r capture.pcap – read captured file

Advanced BPF filters: tcpdump 'tcp[tcpflags] & tcp-syn != 0 and tcp[tcpflags] & tcp-ack == 0' catches only SYN packets (new connections). tcpdump 'icmp[icmptype] = 8' captures only ping requests. Use -s 0 for full packet capture (default 262144 bytes). The -A flag prints ASCII (useful for HTTP headers).

tcpdump and ngrep – String Matching in Packets

ngrep combines tcpdump-like capture with grep-style pattern matching. Example: ngrep -d eth0 "GET /login" port 80 captures HTTP requests to login pages. It supports regular expressions and hexadecimal patterns. Less common but invaluable for quick HTTP debugging.

tshark – Terminal Wireshark

The command-line version of Wireshark. tshark -i eth0 -T fields -e frame.time -e ip.src -e ip.dst -e tcp.port extracts specific fields. tshark -r capture.pcap -Y "http.request" displays only HTTP requests. Use tshark -z io,stat,1 for live throughput statistics.

Performance and Bandwidth Testing

iperf3 – Throughput Measurement

Client-server model: Run iperf3 -s on server, then iperf3 -c server_ip on client. Options:

  • -P 4 – parallel streams
  • -t 30 – test duration in seconds
  • -u – UDP mode (add -b 100m for bandwidth target)
  • -R – reverse mode (server sends, client receives)
  • -i 1 – interval reporting every second

The output shows transfer size, bandwidth, and retransmits (TCP) or jitter/datagram loss (UDP). For bidirectional testing, use --bidir.

nmap – Network Discovery and Security Scanning

Essential for port scanning and service detection. Typical uses:

  • nmap -sT 192.168.1.0/24 – TCP connect scan
  • nmap -sS 192.168.1.1 – SYN stealth scan (requires root)
  • nmap -sV 192.168.1.1 – version detection
  • nmap -O 192.168.1.1 – OS fingerprinting
  • nmap -p 1-1000 example.com – specific port range

NSE Scripts: nmap --script=http-headers example.com checks security headers. nmap -sC runs default scripts. For firewall evasion: nmap -f fragments packets; nmap -D decoy1,decoy2 uses decoy IPs.

sar – System Activity Reporter (Network Module)

Part of sysstat package. sar -n DEV 1 5 shows network interface statistics every second for 5 intervals. Columns include: rxpck/s (receive packets per second), txpck/s, rxkB/s, txkB/s, rxcmp/s (compressed), and %ifutil. sar -n TCP,ETCP 1 shows TCP connection statistics (active opens, passive opens, retransmits). Analyze historical data with sar -f /var/log/sysstat/sa10.

Routing and Advanced Connectivity

ip route – Detailed Routing Control

  • ip route get 8.8.8.8 – show which interface and gateway will be used for a destination
  • ip route flush cache – clear routing cache
  • ip route add 10.0.0.0/8 via 192.168.1.1 dev eth0 table custom – policy routing
  • ip rule show – display routing policy database

route – Legacy Routing (Deprecated)

route -n shows kernel IP routing table with gateway, netmask, and flags (U=up, G=gateway, H=host). route add -net 10.0.0.0 netmask 255.0.0.0 gw 192.168.1.1 adds static route.

arp / arping – Address Resolution Protocol

arp -a displays ARP cache with IP-to-MAC mappings. arp -d 192.168.1.5 removes an entry. arping 192.168.1.1 sends ARP requests to check L2 connectivity (bypasses IP routing). Use arping -c 3 -I eth0 192.168.1.1 for specific interface.

Wireless Networking Tools

iwconfig – Wireless Interface Configuration

iwconfig wlan0 shows ESSID, frequency, bit rate, and signal quality. iwconfig wlan0 essid "MyNetwork" key s:password connects to WEP networks (use wpa_supplicant for WPA/WPA2). iwconfig wlan0 power off disables power saving.

iw – Modern Wireless Tools

Replaces iwconfig. iw dev wlan0 link shows signal strength and connection info. iw dev wlan0 scan lists access points with channels and encryption. iw reg set US sets regulatory domain. iw event shows real-time kernel wireless events (roaming, disconnect).

wpa_supplicant / wpa_cli – WPA Connection Management

wpa_passphrase MyNetwork MyPassword > /etc/wpa_supplicant.conf generates configuration. wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf connects in background. wpa_cli status shows connection state. Interactive mode: wpa_cli then scan_results lists networks.

Network Diagnostics and Testing

curl – HTTP/HTTPS Connectivity

Beyond web pages, curl -v https://example.com provides handshake details including TLS version and certificate chain. curl -w "%{time_total}n" -o /dev/null -s https://example.com measures total response time. curl --trace - https://example.com enables full packet trace.

wget – HTTP/FTP Download Testing

wget -O /dev/null http://testfile.com/100MB.bin tests download speed. wget --spider url checks URL existence without downloading. wget --mirror -p --html-extension example.com downloads entire site.

telnet – Simple Port Connectivity

telnet example.com 80 opens raw TCP connection. Once connected, you can type raw HTTP requests: GET / HTTP/1.1 then press Enter twice. Useful for testing SMTP (port 25), POP3 (110), or any custom protocol. Note: Modern systems may require sudo apt install telnet.

nc (Netcat) – Swiss Army Network Knife

  • Listen mode: nc -lvp 1234 creates a listener on port 1234
  • Port scanning: nc -zv example.com 80-100 checks open ports
  • File transfer: nc -l 1234 > received.file on receiver, nc sender_ip 1234 < file.txt on sender
  • Chat: nc -l 1234 on one machine, nc reciever_ip 1234 on another

openssl s_client – SSL/TLS Testing

openssl s_client -connect example.com:443 -servername example.com shows certificate chain, cipher, and TLS version. openssl s_client -connect example.com:443 -showcerts -tlsextdebug for extended debugging. Test STARTTLS for email: openssl s_client -starttls smtp -connect mail.server:25.

Firewall and Security Commands

iptables / nftables – Packet Filtering

Legacy iptables and modern nftables control packet filtering. Basic iptables:

  • iptables -L -n -v – list rules with packet counts
  • iptables -A INPUT -p tcp --dport 22 -j ACCEPT – allow SSH
  • iptables -A INPUT -s 10.0.0.0/8 -j DROP – block subnet
    For nftables: nft list ruleset shows entire configuration. nft add rule inet filter input tcp dport 80 accept.

ufw – Uncomplicated Firewall

Simplified frontend for iptables. ufw enable/disable, ufw default deny incoming, ufw allow 22/tcp, ufw deny from 192.168.1.100. ufw status numbered lists rules. ufw delete NUM removes by number.

fail2ban – Intrusion Prevention

While not a single command, fail2ban-client controls the protection. fail2ban-client status sshd shows banned IPs. Logs are in /var/log/fail2ban.log. Config files in /etc/fail2ban/ control jail settings (max retries, find time, ban time).

Automation and Scripting Integration

Combining commands in Bash scripts creates powerful network monitoring. Example snippet:

#!/bin/bash
if ! ping -c 1 -W 2 $HOST &> /dev/null; then
    echo "$HOST down at $(date)" >> network.log
    ss -tupn | grep $HOST >> connection.log
fi

Use xargs with parallel tools: nmap -p 80,443 192.168.1.0/24 -oG - | grep open generates machine-readable output.

Troubleshooting Workflow

  1. Check Layer 1/2: ip link show, ethtool eth0
  2. Check Layer 3: ping gateway, traceroute destination
  3. Check DNS: dig example.com, nslookup
  4. Check Firewall: ss -tulpn, iptables -L -n
  5. Check Application: curl -v destination:port, telnet destination port

For persistent issues, capture with tcpdump -w debug.pcap -s 0 -i any port problematic_port and analyze in Wireshark.

Performance Optimization Commands

Check TCP tuning parameters: sysctl net.ipv4.tcp_congestion_control (cubic is default, bbr often better). View socket buffers: sysctl net.core.rmem_max and wmem_max. Monitor TCP retransmissions: nstat -az TcpRetransSegs. Adjust MTU: ip link set eth0 mtu 9000 jumbo (requires switch support). Use ethtool -k eth0 | grep on to verify offload features; disabling large-receive-offload with ethtool -K eth0 gro off can sometimes fix packet drops.


Leave a Reply

Your email address will not be published. Required fields are marked *