Reputation: 613
I've been following a simple UDP server/client tutorial found here, and I have a quick question about which port the client is connecting to the server.
From just viewing the code, it seems quite obvious that the server and client are connecting via port 8888:
Client.cpp
#define SERVER "127.0.0.1" //ip address of udp server
#define BUFLEN 512 //Max length of buffer
#define PORT 8888 //The port on which to listen for incoming data
Server.cpp
#define BUFLEN 512 //Max length of buffer
#define PORT 8888 //The port on which to listen for incoming data
However, when I actually run the server and the client, the server says the client connected port is always different:
First run (Server Log):
Note how the port changes from 8888
Second run (Server Log)
Note how the port changes again
Why would the connected ports change from 8888?
Upvotes: 2
Views: 7770
Reputation: 780974
The comment in the client is incorrect. They just copied that line from the server, but they should have changed it to:
#define PORT 8888 //The port to send outgoing data to
The client and server both put the port in a sockaddr_in
structure. The server uses this structure in its call to bind()
, which sets the listening port. The client uses it in the call to sendto()
, so it sets the destination port.
Since the client never calls bind()
to set a specific local port, the source port is selected arbitrarily from the ephemeral port range. Each socket gets a different port to distinguish them.
If a fixed port were used as the client's local port, you wouldn't be able to have multiple clients on the same machine, since there would be no way to know which client should receive an incoming packet from the server. So fixed ports are typically used for servers, which random ports are used on the client.
Upvotes: 6
Reputation: 73081
When sending a UDP packet from one computer to another, there are two ports involved: the port that the receiving computer's UDP socket is bound to and is receiving on (8888 in your case), and the port that the sending computer is sending from. The port that you see changing is the port that the sending computer is using to send UDP packets from. Since the sending computer never explicitly chooses a UDP port to bind to (i.e. it never calls bind() with a non-zero argument), the sending computer's TCP stack simply picks a currently-available UDP port to implicitly bind the sending UDP socket to, and this port may be different each time the sending program is run.
Upvotes: 4
Reputation: 695
8888 is the server port. The 5 digit port you see on logs are client ports created to eventually get data back from the server. This is an automatic and totally fine mechanism.
Upvotes: 1