Capture incoming traffic in tcpdump

Ricky Robinson picture Ricky Robinson · Apr 24, 2012 · Viewed 72.5k times · Source

In tcpdump, how can I capture all incoming IP traffic destined to my machine? I don't care about my local traffic.

Should I just say:

tcpdump ip dst $MyIpAddress and not src net $myIpAddress/$myNetworkBytes

... or am I missing something?

Answer

Eli Rosencruft picture Eli Rosencruft · Apr 24, 2012

In Bash shell try this:

tcpdump -i eth0 tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes

or this equivalent formulation:

tcpdump -i eth0 ip proto \\tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes

On my system this resolves to something like:

tcpdump -i eth0 tcp and dst host 10.0.0.35 and not src net 10.0.0.0/24

If you want to see all of the traffic to your destination host, not just TCP protocol traffic you could do:

tcpdump -i eth0 dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes

Some notes:

  1. I changed $myIpAddress/$myNetworkBytes to $MyNetworkAddress/$myNetworkBytes. This is because the apparent intent of your rule is to exclude traffic from your local network, and the correct way to specify a network address is to specify the network's lowest IP address (which is called the network address) / netmask. If you specify any address other than the lowest address in the range for a network with a netmask of $myNetworkBytes, then you will get the error message:

    tcpdump: non-network bits set in "10.0.0.3/24"
    
  2. In the first example 'tcp' is a keyword in the libpcap expression language (man pcap-filter) , whereas in the second example, 'tcp' is used as a value of ip proto. In order to indicate that the 'tcp' in the second instance is a value and not another 'tcp' keyword, I need to escape the 'tcp' with a double backslash. It has to be a double backslash so that the Bash interpreter will pass a single backslash on to the libpcap interpreter (Bash eats the first backslash, libpcap gets the second.) To reduce the double escape confusion, it might be good to get into the habit of double quoting the entire expression part of the command:

    tcpdump -i eth0 "ip proto \tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes"
    
  3. To avoid warnings and surprises, it is better to use the interface specifier -i eth0 or whatever interface you wish. Not all interfaces necessarily have an IP address assigned and without being specific, you might see traffic that you hadn't intended to see. This is especially true on systems that have the network-manager running, which seems to have its own mind about what interfaces to add and when.