Reputation: 29066
I am trying to do a simple client/server chat example using UDP
sockets.
The idea is to have 2 applications running on 2 different PCs. Each program is both client and server.
The server is bind on 0.0.0.0
port 9999
and the client is using as well the port 9999
.
client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
other_address.sin_family = AF_INET;
other_address.sin_port = htons(9999);
other_address.sin_addr.s_addr = inet_addr(192.168.1.42);
sendto(client_socket, data, size,
0, other_address, sizeof(struct sockaddr_in));
On Wireshark I can see the origin port is random chosen from 53783 to 57229.
Source Destination Protocol Info
192.168.1.6 192.168.1.42 UDP 57229 -> 9999
192.168.1.42 192.168.1.6 UDP 53783 -> 9999
What is my mistake?
Upvotes: 0
Views: 1846
Reputation: 73041
What is my mistake?
If you want your UDP packets to be sent from a port that you choose, you'll need to call bind() on your sending UDP socket to specify the (non-zero) port that you want the socket to be sending from (and listening on). If you don't, then the OS will choose an available port to send from, as you have seen.
Note that that isn't necessarily a bad thing: it's often preferable to let the OS choose a port for you, since that way you avoid the possible failure that would occur if the port you specified was unavailable because some other program was already using it. The receiving (server) program can read in the UDP packets using recvfrom() to find out the IP address and port number they came from, so there's no reason it can't reply to your UDP packets even if your UDP packets aren't coming from a "well-known" port.
Upvotes: 3