Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket programming - What's the difference between listen() and accept()?

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().

like image 650
Zen Hacker Avatar asked Dec 03 '15 18:12

Zen Hacker


People also ask

What is socket () bind () listen () accept () and connect ()?

The steps involved in establishing a TCP socket on the server side are as follows: Create a socket with the socket() function; Bind the socket to an address using the bind() function; Listen for connections with the listen() function; Accept a connection with the accept() function system call.

What does listen do in sockets?

The listen() call indicates a readiness to accept client connection requests. It transforms an active socket into a passive socket. Once called, socket can never be used as an active socket to initiate connection requests. Calling listen() is the third of four steps that a server performs to accept a connection.

What is the difference between bind () and listen ()?

bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local IP address and a port number. listen() is used on the server side, and causes a bound TCP socket to enter listening state.

Can a socket accept without listening?

No and no. The socket isn't put into listening mode until you call listen() . It must be listening in order to accept() . And, once you're listening, you cannot convert the socket to a connected socket.


1 Answers

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.

like image 180
Some programmer dude Avatar answered Sep 21 '22 11:09

Some programmer dude