Can 'Connect' Call on Socket Return Successfully Without Server Calling 'Accept'

Can 'connect' call on socket return successfully without server calling 'accept'?


If I understand correctly, 'connect' returns only after server does 'accept' on the listening socket. Am I missing something here?

Yes. TCP establishes the connection - the 3-way handshake - under the covers and puts it in a completed connection queue when it is ready. Accept() returns the next waiting connection from the front of this queue.

From the client's perspective it is "connected" but it won't be talking to anyone until the server accepts and begins processing. Sort of like when you call a company and are immediately put in the hold queue. You are "connected" but no business is going to be done until someone actually picks up and starts talking.

Your individual thread may have died but the process is still alive and the file descriptor still open so TCP doesn't know what is going on at the application level.

Client Calling connect() without server calling listen()

Your code is mostly correct. However, you need to close and recreate the socket on each loop iteration (see Does socket become unusable after connect() fails?), eg:

for(int j = 0; j < argc-3; j++){
//sockfd of each server needed to be connect()ed is stored in array all_sock_fd[]
int sockfd;
while (1)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("could not create socket");
return 1;
}

sender_conn = connect(sockfd, (struct sockaddr *)&all_sockaddrs[j], sizeof(all_sockaddrs[j]));
if (sender_conn == 0) break;

// examine errno and decide whether it is reasonable to continue retrying

close(sockfd);

//wait a few seconds and try again
sleep(5);
}

//connection successful, create a thread for that connection
all_sock_fd[j] = sockfd;
if (pthread_create(&thread_id, NULL, you_connect_to_others, (void*) &all_sock_fd[j]) < 0)
{
perror("could not create thread");
close(all_sock_fd[j]);
all_sock_fd[j] = -1;
return 1;
}
}

C++ sockets: accept() hangs when client calls connect(), but accept() responds to HTTP GET request

Contrary to the typical port forwarding done in the local router, ngrok is not a port forwarder at the transport level (TCP) but it is a request forwarder at the HTTP level.

Thus if the client does a TCP connect to the external ngrok server nothing will be forwarded yet. Only after the client has send the HTTP request the destination will be determined and then this request will be send to the ngrok connector on the internal machine, which then will initiate the connection to the internal server and forward the request.



Related Topics



Leave a reply



Submit