哪个进程拥有给定的端口(Linux内核)? [英] Which process owns the given port (Linux kernel)?

查看:100
本文介绍了哪个进程拥有给定的端口(Linux内核)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Linux编写一个简单的应用程序层防火墙(到目前为止,还算是我需要的东西).由于iptables的所有者模块还不够,我决定使用libnetfilter_queue来实现.在防火墙(C/C ++应用程序)的某个时刻,我需要决定是否接受具有给定src/dest端口的数据包.现在出现了问题.是否有任何简便的方法来知道哪个进程拥有给定的端口?

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)

似乎在用户空间中执行此操作的唯一方法是解析/proc层次结构.我不想这样做,因为使用所有临时端口可能会很慢.内核必须在TCP堆栈中具有某种map port-> process.是否有可能通过一个定制的内核模块来实现?也许有人可以指出我要完成另一项任务的另一种方式?

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?

推荐答案

对自己的回答.

内核模块tcp_diag使文件proc/net/tcp可用.它提供了所有TCP套接字及其状态的随时可用列表.

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.

将套接字映射到进程的最佳方法是通过/proc/*/fd/*中的文件描述符,因为套接字可能被同时使用它们的许多进程/线程共享. iproute2软件包中ss实用程序的源代码是学习这些知识的好地方.

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.

这篇关于哪个进程拥有给定的端口(Linux内核)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆