gpt4 book ai didi

sockets - 从 'struct sock'导出套接字fd

转载 作者:行者123 更新时间:2023-12-03 11:57:50 25 4
gpt4 key购买 nike

有没有办法从内核中的struct sock类型的对象获取套接字fd?快速浏览struct sock内部无助于查找类似于套接字描述符的内容。基本上我需要socket() syscall返回的内容,它不存储在'sock'中吗?

我需要在数据包到达IP堆栈之前的那一刻获取fd

谢谢。

最佳答案

对于每个进程,都有一个文件描述符的表,该表将文件描述符映射到struct file对象。您可以使用iterate_fd()函数在此表上进行迭代。

对于任何struct file,您可以使用struct sock函数确定其对应的sock_from_file()对象。

总共:

/*
* Callback for iterate_fd().
*
* If given file corresponds to the given socket, return fd + 1.
* Otherwise return 0.
*
* Note, that returning 0 is needed for continue the search.
*/
static int check_file_is_sock(void* s, struct file* f, int fd)
{
int err;
struct sock* real_sock = sock_from_file(f, &err);
if(real_sock == s)
return fd + 1;
else
return 0;
}
// Return file descriptor for given socket in given process.
int get_fd_for_sock(struct sock* s, struct task* p)
{
int search_res;
task_lock(p);
// This returns either (fd + 1) or 0 if not found.
search_res = iterate_fd(p->files, 0, &check_file_is_sock, s);
task_unlock(p);

if(search_res)
return search_res - 1;
else
return -1; // Not found
}

关于sockets - 从 'struct sock'导出套接字fd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44005982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com