How can I capture network traffic of a single process?

I would like to examine the network traffic being handled by a single process, but simple network captures won't work since I am dealing with such a busy system (lots of other traffic happening at the same time). Is there a way to isolate a tcpdump or wireshark capture to the networking traffic of a single specific process? (Using netstat is insufficient.)


Solution 1:

To start and monitor an new process:

strace -f -e trace=network -s 10000 PROCESS ARGUMENTS

To monitor an existing process with a known PID:

strace -p $PID -f -e trace=network -s 10000
  • -f is for "follow new processes"
  • -e defines a filter
  • -s sets the limit of strings to more then 32
  • -p takes the process id to attach to

Solution 2:

I know this thread is a bit old but I think this might help some of you:

If your kernel allows it, capturing the network traffic of a single process is very easily done by running the said process in an isolated network namespace and using wireshark (or other standard networking tools) in the said namespace as well.

The setup might seem a bit complex, but once you understand it and become familiar with it, it will ease your work so much.

So as to do so:

  • create a test network namespace:

    ip netns add test
    
  • create a pair of virtual network interfaces (veth-a and veth-b):

    ip link add veth-a type veth peer name veth-b
    
  • change the active namespace of the veth-a interface:

    ip link set veth-a netns test
    
  • configure the IP addresses of the virtual interfaces:

    ip netns exec test ifconfig veth-a up 192.168.163.1 netmask 255.255.255.0
    ifconfig veth-b up 192.168.163.254 netmask 255.255.255.0
    
  • configure the routing in the test namespace:

    ip netns exec test route add default gw 192.168.163.254 dev veth-a
    
  • activate ip_forward and establish a NAT rule to forward the traffic coming in from the namespace you created (you have to adjust the network interface and SNAT ip address):

    echo 1 > /proc/sys/net/ipv4/ip_forward
    iptables -t nat -A POSTROUTING -s 192.168.163.0/24 -o <your internet interface, e.g. eth0> -j SNAT --to-source <your ip address>
    

    (You can also use the MASQUERADE rule if you prefer)

  • finally, you can run the process you want to analyze in the new namespace, and wireshark too:

    ip netns exec test thebinarytotest
    ip netns exec test wireshark
    

    You'll have to monitor the veth-a interface.