#!/bin/bash function monitor_traffic() { if [ -z "$1" ]; then echo "Usage: $0 " echo "Available network interfaces:" ip link show | awk -F': ' '/^[0-9]+: /{print $2}' exit 1 fi INTERFACE=$1 DURATION=10 # Duration in seconds for each capture window # Output header only once printf "IP Address\tDownload (bytes)\tUpload (bytes)\n" # Handle SIGINT (Ctrl+C) to gracefully exit the loop trap "echo 'Exiting...'; exit 0" SIGINT while true; do # Temp file to store tcpdump output TMP_FILE=$(mktemp) trap "rm -f $TMP_FILE" EXIT # Ensure cleanup on exit or interruption # Capture IPv4 traffic on the specified interface for the specified duration sudo timeout $DURATION tcpdump -i $INTERFACE -nn -q -tt 'ip' > $TMP_FILE 2>/dev/null # Calculate traffic statistics awk ' /IP/ { # Extract source and destination IPs using a stricter pattern to ensure only IPs are captured if (match($3, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) { src_ip = substr($3, RSTART, RLENGTH) } if (match($5, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) { dst_ip = substr($5, RSTART, RLENGTH) } # Calculate packet size (bytes) - field 8 (better validation) size = $NF if (size ~ /^[0-9]+$/) { # Count download (dst_ip) and upload (src_ip) for traffic download[dst_ip] += size upload[src_ip] += size } } END { # Create a combined total_bytes array for sorting for (ip in download) { total_bytes[ip] = download[ip] + upload[ip] } # Sort IPs by total bytes in descending order n = asorti(total_bytes, sorted_ips, "@val_num_desc") for (i = 1; i <= n; i++) { ip = sorted_ips[i] download_data = download[ip] > 0 ? download[ip] : 0 upload_data = upload[ip] > 0 ? upload[ip] : 0 printf "%-15s\t%-15d\t%-15d\n", ip, download_data, upload_data } }' $TMP_FILE # Print separator line echo "=======================================" # Clean up the temporary file rm -f $TMP_FILE done } # Call function with passed argument (network interface) monitor_traffic $1