stackunderflow
stackunderflow

Reputation: 907

what's the host port number when we use accept() and connect() in C socket programming

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

Answers (4)

user207421
user207421

Reputation: 310840

It does not assign a new port. The accepted socket uses the same port as the listening socket.

Upvotes: 1

netskink
netskink

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

rushman
rushman

Reputation: 562

I think getpeername will return this information

Upvotes: 1

Remy Lebeau
Remy Lebeau

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

Related Questions