#!/bin/bash function get_top_ip() { 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=180 # Duration in seconds (3 minutes) # Temp file to store tcpdump output TMP_FILE=$(mktemp) trap "rm -f $TMP_FILE" EXIT # Ensure cleanup on exit # Capture IPv4 traffic on the specified interface echo "Capturing network traffic on $INTERFACE for $DURATION seconds..." sudo timeout $DURATION tcpdump -i $INTERFACE -nn -q -tt 'ip' > $TMP_FILE echo "Processing captured traffic data..." # 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 { print "Top 10 IPs by Traffic:" printf "%-15s\t%-15s\t%-15s\n", "IP Address", "Download (bytes)", "Upload (bytes)" for (ip in download) { total_bytes[ip] = download[ip] + upload[ip] } n = asorti(total_bytes, sorted_ips, "@val_num_desc") for (i = 1; i <= 10 && i <= n; i++) { ip = sorted_ips[i] download_data = download[ip] > 0 ? download[ip] " bytes" : "0 bytes" upload_data = upload[ip] > 0 ? upload[ip] " bytes" : "0 bytes" printf "%-15s\t%-15s\t%-15s\n", ip, download_data, upload_data } }' $TMP_FILE } # Call function with passed argument (network interface) get_top_ip $1