tags:

views:

603

answers:

3

Hi,

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.

-Prabhu

+8  A: 

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!

Darron
+1  A: 

I believe that Darron meant getsockname(). This is what you want if you need to determine the port number on the client side (the side calling connect()) programmatically. On the server side (the side calling bind()), you would use getpeername() to get the same information from the connected socket.

However, if you are debugging and can't change the code, then you end up using things like the netstat or sockstat utility depending on the operating system. I'm not sure what utilities are available under Linux (or even your particular package) but I would start with man sockstat. If it's installed, you can run it from either side and see which endpoints have been assigned to which processes. Combine this with grep and you can usually figure out which address to filter on in Ethereal. Good luck!

D.Shawley
A: 
lsof -p <process id> | grep TCP
Scott