views:

158

answers:

4

EDIT: Restating the problem, if I am listening to port 54321 and a local process listening to port 12345 connects to me, creating socket s, how do I actually find the port it is listening on?

sockaddr_in addr;
int len = sizeof(addr);
getpeername(s, (sockaddr*)&addr, &len);
cout << string(inet_ntoa(addr.sin_addr)) << ":" << ntohs(addr.sin_port) << endl;

Shouldn't the output be 127.0.0.1:12345? Instead I get 127.0.0.1:62305, or some other arbitrary port number. Is this an error on my part, or is it supposed to be this way?

A: 

getpeername give details about the client not the server so it make sense you get some random port.

you can see the man page

Cheers

RageZ
+1  A: 

To elaborate on RageZ's answer, getpeername() is returning the source port and address of the other side of your socket. Port 12345 is the address of the destination that you passed to bind(). In general, clients (e.g. telnet, nc, etc...) will not have called bind() on their socket because they don't want to listen for connections. So the OS will assign them an arbitrary "ephemeral" port number.

In general, there is little to no utility in knowing the source port of a TCP connection.

Andy Ross
A: 

You should get 127.0.0.1:12345 if s is connected. Are you sure it's connected?

You need to check return code of getpeername() to make sure there is no errors.

ZZ Coder
+2  A: 

It looks like you have two processes listening on two ports - that's two listening sockets independent of each other. Then you create a third, client, socket in one of the processes and connect to the other one. That third socket gets an ephemeral port assigned to it by TCP stack (62305 in your case). So the connection is represented by the tuple {source ip, source port, target ip, target port} - {127.0.0.1,62305,127.0.0.1,54321} here. This connection has absolutely nothing to do with any listening sockets the connecting process might have. You have to explicitly design your application to communicate port numbers among peers if you need to know them. If you just want to know what process has what sockets, there's always lsof.

Nikolai N Fetissov
Gotcha, this is the mistake I was making in my reasoning. I figured when I use connect(), the resulting connection is somehow "associated" with the port I'm listening to, and will send/receive data over the same port. Thanks for the clarification.
oskar