Linux – Determining the TCP port number to which client got bound


I create a TCP socket without bothering about the port number to bind to [socket.sin_port = 0]. However later on if I want to print the port number of client how do I do that? The client C application (on Linux) creates many clients which get connected to server. To debug issues I capture the traffic on ethereal. I thought of printing the port number in logs while issue arises so that filtering on ethereal becomes easy.

Any help would be appreciated.


Best Solution

Use the getsockname() call to get the socket address and port after a successful connection.

Edit: correct method name. Sometimes I can't copy a simple word from one window to another!