Need to find the pid of the process that owns caught packet.

Is there any way to do it without long parsing /proc/net/tcp and /proc/<PID>/fd/? Maybe, need to sniff packets in another way? I have to find the fastest way to correlate the packet and its master process in C.

  • My call is "leave open", as getting information about network connections known to the OS is very much specific to the services and interfaces provided by the OS, and not a programming issue in general. Of course the question could be edited to remove the reference to the C language, but it's still going to be the natural language to use for accessing Linux system calls. (File interfaces are easy to access in other ways, of course.) – ilkkachu Mar 22 '17 at 12:34
  • @ilkkachu I am voting to migrate to Stack Overflow because the question is not “how to find this information” (on-topic on Unix & Linux) but “how to find it easily in my preferred programming language” (off-topic since it's about programming in that particular language). – Gilles Mar 22 '17 at 21:42
  • @Gilles, No, the question is "how to do it without parsing files". C is just a hint that the way of parsing output of some utilities (netstat or something like that) in bash or perl is not the answer. – marar Mar 27 '17 at 15:17
  • That's the point: you want a specific technique that's easy in a particular programming language. In a shell script, parsing a file or calling a utility would be the natural way. ilkkachu's answer is exactly what you should expect here. If you want an easier C implementation than parsing the output of netstat, you should ask on Stack Overflow. – Gilles Mar 27 '17 at 22:52

I don't think there is any other way, /proc/net/* and /proc/*/fd/ seem to be what lsof and netstat -p read. Having a unique mapping from sockets (or tcp ports) to processes would also be impossible since multiple processes can have copies of the same socket. netstat -p seems to show only one of those, lsof of course lists all. Also, since you're starting from a packet, it might not have an originating socket at all: it could come from outside the system, or from a raw/packet socket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.