amazingjxq
amazingjxq

Reputation: 4677

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?

Upvotes: 4

Views: 6942

Answers (2)

SKi
SKi

Reputation: 8466

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.

Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129344

I believe you you can use this: http://www.catonmat.net/blog/traffic-accounting-with-iptables/

You just have to edit the awk script a little bit to print the number of packets rather than number of bytes [and print IP address second rather than first if that is critical].

Upvotes: 0

Related Questions