派生出来自' struct sock'

时间:2017-05-16 15:44:43

标签: sockets networking linux-kernel system-calls

有没有办法从内核中的struct sock类型的对象获取套接字fd?快速查看struct sock内部并没有帮助找到看起来像套接字描述符的东西。基本上我需要socket()系统调用返回的内容,是否存储在' sock' ?

我需要在数据包到达IP堆栈之前得到fd

感谢。

1 个答案:

答案 0 :(得分:3)

对于每个进程,都有一个文件描述符表,它将文件描述符映射到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
}