Usually it does not matter which source port you send data from as a client, but I still want to do it for some testing. So I tried to bind my client's socket to a specific port but even when I'm running client and server on my local machine (with localhost as dest address) the server tells me that my source port is something like 59000. I initialize my socket like this:
tcp::socket socket(io_service,tcp::endpoint(tcp::v4(),2000));
Is it possible to do what I intend? I'm trying to find out if my router changes ports when the message goes through it. Thats for NAT traversal stuff I'm playing around with at the moment.
Binding a socket to a specific port can be done exactly as posted in the question:
In this case, the
socket
object will be constructed, opening and binding to the local endpoint with an address ofINADDR_ANY
and port2000
.The local endpoint is likely changing as a result of how the connection is being established. When the connect operation is initiated from either the
socket.connect()
orsocket.async_connect()
member functions, the socket will attempt to connect to the remote endpoint, opening the socket if necessary. Therefore, when invoked on a socket that is already open, the socket's local endpoint will not change.On the other hand, when the connect operation is initiated from either
connect()
orasync_connect()
free functions, the socket is closed before attempting to connect to any endpoint. Thus, the socket will bind to an unspecified port. The parameter section on the free functions documentation defines this behavior:Furthermore, there is no clean way to control this behavior, as the
socket.close()
andsocket.connect()
member functions are invoked one after another within the implementation.Here is a complete example demonstrating the behaviors described above:
Which produced the following output: