Mark As Completed Discussion

To accept an incoming connection on a socket, you need to perform the following steps:

  1. Create a new socket using the socket() function, just like in the previous step.

    TEXT/X-C++SRC
    1int sockfd, newSockfd;
    2sockfd = socket(AF_INET, SOCK_STREAM, 0);
  2. Set up the server address, as mentioned before.

  3. Bind the socket to the server address, as mentioned before.

  4. Make the socket listen for connections, as mentioned before.

  5. Call the accept() function to accept an incoming connection. This function blocks until a connection is made. You pass the listening socket descriptor, the client address structure, and the length of the client address structure as parameters.

    TEXT/X-C++SRC
    1socklen_t clientAddrLen;
    2newSockfd = accept(sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
  6. If the accept() function returns a valid socket descriptor, it means a connection has been successfully established.

    TEXT/X-C++SRC
    1if (newSockfd == -1) {
    2  std::cout << "Failed to accept connection" << std::endl;
    3  return 1;
    4}
    5
    6std::cout << "Accepted connection from client" << std::endl;

Remember to handle any errors that might occur during the accept process and close both the listening socket and the new socket when you're done.

Here's an example code that demonstrates how to accept an incoming connection on a socket:

SNIPPET
1#include <iostream>
2#include <sys/socket.h>
3#include <netinet/in.h>
4
5int main() {
6  // ... code from previous steps ...
7
8  // Accept incoming connections
9  clientAddrLen = sizeof(clientAddr);
10  newSockfd = accept(sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
11
12  if (newSockfd == -1) {
13    std::cout << "Failed to accept connection" << std::endl;
14    return 1;
15  }
16
17  std::cout << "Accepted connection from client" << std::endl;
18
19  return 0;
20}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment