I've been reading this tutorial to learn about socket programming. It seems that the listen()
and accept()
system calls both do the same thing, which is block and wait for a client to connect to the socket that was created with the socket()
system call. Why do you need two separate steps for this? Why not just use one system call?
By the way, I have googled this question and found similar questions, but none of the answers were satisfactory. For example, one of them said that accept()
creates the socket, which makes no sense, since I know that the socket is created by socket()
.
The listen()
function basically sets a flag in the internal socket structure marking the socket as a passive listening socket, one that you can call accept
on. It opens the bound port so the socket can then start receiving connections from clients.
The accept()
function asks a listening socket to accept the next incoming connection and return a socket descriptor for that connection. So, in a sense, accept()
does create a socket, just not the one you use to listen()
for incoming connections on.