I use the Winsock2 and Ws2tcpip libraries.
IDE - VS15
OS - Windows8

  • 2
    so the port on which to listen determines the server - the client of the unknowable port will not be able to connect ... - ampawd
  • and there are no cases when it is possible to connect to a server via different ports? - helldrg
  • happen but you yourself ask these ports. - Alex.B
  • Here I am trying to display port_client = ntohs (client_addr.sin_port); But the other port is displayed - helldrg
  • Are you sure you understand correctly how applications with a client-server architecture work? But this is not the main thing - where is your code? - isnullxbh

1 answer 1

You can see this:

int srcs_size = sizeof( src_addr ); if ( getsockname( my_sock, (struct sockaddr *)&src_addr, &srcs_size ) == 0 ) { int src_port = ntohs( src_addr.sin_port ); } 

Because we are now talking about the client side, it is clear that we have ephemeral ports - here I have a question for you - what did you compare with, if you didn’t know how to look at the port number in the code?))

UPD: here, in general, not all the conditions, but I think, as a learning example, it will do. And this code should be used after the connect function has been called.

But as for netstat'a:

enter image description here

Well, agree - it is convenient, right? And you can check without a client.

  • Ports everywhere are real, not ephemeral. The connect system essentially makes bind with one of the free ports with the client's socket (if we ourselves had not explicitly specified the port yet by calling bind). - avp
  • @avp, sorry, did not quite understand you. How do you understand the word "ephemeral"? - isnullxbh
  • @avp, when I say "ephemeral", I point out the time of their life, because clients use dynamically assigned ports. That is, in fact, why I didn’t understand what “real” means? - isnullxbh
  • I understand the ephemeral as not real, for the ports it would be a port from another "pool", similar to the memory addresses from the address spaces of different processes. Here, the port is selected from the same ports that are available for all other connections. And the “lifetime” of such a port is no different from the “lifetime” of an obviously busy (bind) programmer. - avp
  • Understood you, perhaps I am not right, using this terminology in the context of Windows. Maybe. However, in the book (s) of Stevens, such ports are called this way. I looked at the meaning of the word ephemeral - indeed, it can be interpreted as illusory , but there is also a short-lived meaning, which, in general, explains its use in the above-mentioned book. - isnullxbh