To accept an incoming connection on a socket, you need to perform the following steps:
Create a new socket using the
socket()
function, just like in the previous step.TEXT/X-C++SRC1int sockfd, newSockfd; 2sockfd = socket(AF_INET, SOCK_STREAM, 0);
Set up the server address, as mentioned before.
Bind the socket to the server address, as mentioned before.
Make the socket listen for connections, as mentioned before.
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++SRC1socklen_t clientAddrLen; 2newSockfd = accept(sockfd, (struct sockaddr*)&clientAddr, &clientAddrLen);
If the
accept()
function returns a valid socket descriptor, it means a connection has been successfully established.TEXT/X-C++SRC1if (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:
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}
xxxxxxxxxx
}
int main() {
int sockfd, newSockfd;
struct sockaddr_in serverAddr, clientAddr;
socklen_t clientAddrLen;
// Create a socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
std::cout << "Failed to create socket" << std::endl;
return 1;
}
// Set up the server address
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(8080);
// Bind the socket
int bindResult = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if (bindResult == -1) {
std::cout << "Failed to bind socket" << std::endl;
return 1;
}