Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Linux kernel have `struct sock` and `struct socket`?

This questions was asked before on the Internet, but I couldn't find a good answer.

The Linux kernel networking stack features two structures:

  • struct socket, generally stored in a variable sock
  • struct sock, generally stored in a variable sk

The two structures are essentially linked, but seem to have slightly different lifetimes. One can find an sk via sock->sk, or find a sock via sk->sk_socket.

Why are there two structures to store information about sockets? Assuming I need to add a new field, when would I add it to struct socket and when to struct sock?

UPDATE: Please note that I refer to struct socket in include/linux/net.h inside the Linux source code, which is meant for kernel code only, and not /usr/include/sys/socket.h which is meant for userland.

like image 313
user1202136 Avatar asked Sep 19 '17 08:09

user1202136


1 Answers

struct socket seems to be a higher level interface that is used for system calls (that is why it also has pointer to struct file which represents file descriptor here).

struct sock is a in-kernel implemenation for AF_INET sockets (there is also struct unix_sock for AF_UNIX sockets which is derivative of this) which can be used both by kernel and by userspace (via struct sock).

Both were added to Linux 1.0 back in 1993, I doubt you'll find a doc specifying initial design decision.

like image 91
myaut Avatar answered Sep 17 '22 10:09

myaut