Reputation: 907
the Beej's Guide to Network Programming explains the accept() as follows:
What's going to happen is this: someone far far away will try to connect() to your machine on a port that you are listen()ing on. Their connection will be queued up waiting to be accept()ed. You call accept() and you tell it to get the pending connection. It'll return to you a brand new socket file descriptor to use for this single connection!
but how do we know the port number of the "brand new socket"?
Upvotes: 2
Views: 1208
Reputation: 310840
It does not assign a new port. The accepted socket uses the same port as the listening socket.
Upvotes: 1
Reputation: 4539
From the GNU docs on accept.
newfd = accept (sockfd, (struct sockaddr *) &clientname, &size);
if (newfd < 0) {
perror ("accept");
exit (EXIT_FAILURE);
}
In the accept sockaddr.in struc, you find the local port.
fprintf (stderr, "Server: connect from host %s, port %hd.\n",
inet_ntoa (clientname.sin_addr),
ntohs (clientname.sin_port));
Upvotes: 1
Reputation: 595339
Pass the accepted SOCKET
to getsockname()
to retreive its local IP/Port, and to getpeername()
to retreive its remote IP/Port.
Upvotes: 1