Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which process owns the given port (Linux kernel)?

I am writing a simple application layer firewall for Linux (nothing fancy for now, just sth I need). As the owner module for iptables isn't sufficient, I decided to do it with libnetfilter_queue. At some point in my firewall (C/C++ application) I need to decide wheather the packet with given src/dest port is to be accepted or not. Now comes the question. Is there any easy/fast way of knowing which process owns given port?

Basically, I need a function

pid_t port2pid(u_int16_t port)

It seems the only way to do it in userspace is to parse the /proc hierarchy. I don't want to do that, as it may be slow with all the ephemeral ports. The kernel must have some kind of map port->process in the TCP stack. Is it possible to get to that through, say, a custom kernel module? Maybe someone can point me to another way of accomplishing the same task?

like image 760
Michał Goliński Avatar asked Mar 16 '26 12:03

Michał Goliński


1 Answers

Answering to self.

The file proc/net/tcp is made available by the kernel module tcp_diag. It gives a readily available list of all TCP sockets and their state.

The best way to map the sockets to processes is through the file descriptors in /proc/*/fd/*, as the socket might be shared by many processes/threads that use them concurrently. Source to the ss utility from the iproute2 package is a good place to learn this stuff.

like image 100
Michał Goliński Avatar answered Mar 18 '26 01:03

Michał Goliński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!