Dhruv Shah
Dhruv Shah

Reputation: 45

accept() function in C for network programming

Why does accept() function call initialize a new socket instead of using the same socket we made using socket() function call. I am working on TCP client-server program.

int welcomeSocket, newSocket;
welcomeSocket = socket(PF_INET, SOCK_STREAM, 0); //socket initialized..

// initializing different structure values..

bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
listen(welcomeSocket,5);

/*---- Accept call creates a new socket for the incoming connection ----*/
addr_size = sizeof serverStorage;
newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage,&addr_size);
send();

// why accept makes a new socket?????

Upvotes: 0

Views: 849

Answers (1)

Vatine
Vatine

Reputation: 21248

Because the original socket you created needs to stay around, so you can accept multiple simultaneous connections.

The socket returned by accept is not your "listening socket", it is a socket that on the other end has a communicating peer connected.

Upvotes: 2

Related Questions