Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of packets received from a specific host?

I want to inspect which host is sending the most traffic to my server. How can I get something like this:

172 192.168.1.1
19  192.168.1.56

Which means that in a specific time interval, my serve received 172 packets from 192.168.1.1 and 19 packets from 192.168.1.56.

How can I do this?

like image 679
amazingjxq Avatar asked Feb 02 '26 05:02

amazingjxq


1 Answers

You could try to use tcpdump for that:

#!/bin/sh

while [ 1 ]
do
  timeout -t 5 tcpdump -n -i eth0 "tcp port 22" 2> /dev/null > /tmp/capture.txt
  echo
  date
  cat /tmp/capture.txt | grep -oE "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" | sort | uniq -c
done

It will produce periodic statistics by counting IPv4 addresses from the output of tcpdump.

With pcap filter, you can easily limit what traffic is wanted. In the example script "tcp port 22" limits traffic to SSH.

Example output:

Fri Jun 28 16:05:10 UTC 2019
     53 10.0.0.2
     53 10.0.0.99

Fri Jun 28 16:05:16 UTC 2019
     37 10.0.0.2
     37 10.0.0.99

Fri Jun 28 16:05:21 UTC 2019

Fri Jun 28 16:05:26 UTC 2019
      5 10.0.0.2
      5 10.0.0.99

Because tcpdump is not running all the time, the counting may lose some packets sometimes.

like image 83
SKi Avatar answered Feb 04 '26 00:02

SKi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!