Linux – How to capture network packets per PID

linuxnetworking

Anyone know an easy way to ask Linux to "display every internet packet to/from google chrome" or "display every internet packet to/from telnet process with PID 10275"?

The telnet example is not too useful, since I can just use wireshark or tcpdump to see all TCP conversations involving port 23. That and nobody uses telnet anymore. But sniffing all packets to/from complex applications which use many ports seems like a useful thing.

I found some related answers exploring different ways to corroborate ports and PIDs (or programs names) and such, but nothing about packets

Looks like someone might have been willing to pay for this answer a while back:

NetHogs is useful for quickly seeing what programs are creating traffic over an interface, but it doesn't have a way to capture packets.

Best Answer

Not directly a tcpdump, but can give you info about the network traffic, check https://bytefreaks.net/gnulinux/how-to-capture-all-network-traffic-of-a-single-process

strace -f -e trace=network -s 10000 <PROCESS WITH ARGUMENTS>;

If the process is already started and you know its PID you can use the following 1

strace -f -e trace=network -s 10000 -p <PID>;

Another alternative is more complex, using network namespaces, check the above link or use the tool nsntrace, but either can only work on new process, you can not change existent process network namespaces (AFAIK)

UPDATE: you can also install the tool bpfcc-tools (search for your distro, many have it included already) and use the command sudo tcptracer-bpfcc -v -p (PID) While this will not show the packets, it will list network connections for that pid. You can remove the -p (PID) to list all connections per process. This may be useful for those tracking short live connections, not the network payload.