r/cprogramming • u/Param-Matharoo • Aug 03 '26
What's the Internal working of Socket system call ?
Basically I am creating my own http.web server for that I need to create TCP web server first and during that thing I get to know about socket(), bind(), listening() system calls and I am curious about these system calls internal working like what is happening under the hood.
8
Upvotes
7
u/non-existing-person Aug 03 '26
socketcreates new file descriptor and allocates memory for specific operation and protocol.bindattaches/assigns socket to network address (ip and port for tcp/udp), anything that is received on that address is passed to your socketlistenmarks socket for incoming TCP connection, you will be able to react to TCP handshake withacceptfunction.For really in depth understanding you should visit https://elixir.bootlin.com/linux/v7.1.5/source
Or it may be easier to analyze tcp/ip stack for embedded: https://github.com/lwip-tcpip/lwip which should be a bit simpler than Linux one.
Good idea might be to compile lwip with debug symbols and no optimization, and just step through the code with gdb. You can do that with qemu simulating zephyr or nuttx.
2
u/Blah-Blah-Blah-2023 Aug 03 '26
If you want a simple implementation, go look at the Minix source code.
2
u/sciencekm Aug 03 '26
You can read the implementation to get an understanding on how sockets work under the hood.
https://github.com/torvalds/linux/blob/master/net/socket.c
1
u/StephenRoylance Aug 03 '26
best thing you can do is read 'understanding the linux kernel'. its older, but the foundation is solid. you really don't need to read the code either, the prose is enough to help you understand.
and a TL;DR, nothing magic, its all just more software. IP is stateless, so that and the network card driver and pretty much simple shims that move data from one layer to the next. TCP is where it gets complicated. the kernel keeps track of all the state for you and manages your socket like it manages file descriptors.
1
u/theNbomr Aug 03 '26
Every implementation will differ according to the platform. The only really important thing is that it implements the standard API. Even that can have variations that accommodate the particular platform. The differences typically relate to constraints imposed by simple hardware or OS support (multitasking vs single tasking, for example). There are a number of open source offerings across the range of platforms for your scrutiny.
1
u/duane11583 Aug 03 '26
i suggest you look at the linux device driver file api.
its just a bunch of call backs the driver creates