I am looking at some simple example of sending and receiving messages over datagram sockets.
Server side code.
sock = socket(AF_INET, SOCK_DGRAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr_len = sizeof(struct sockaddr);
if (bind(sock, (struct sockaddr*)&server_addr, addr_len) < 0)
exit(1);
printf("Receiving data ... \n");
bytes_read = recvfrom(sock, recv_data, 1024, 0, (struct sockaddr*)&client_addr, &addr_len);
printf("Server received: %s\n", recv_data);
printf("Sending data ... \n");
sendto(sock, send_data, strlen(send_data) 1, 0, (struct sockaddr*)&client_addr, addr_len);
Client side code.
sock = socket(AF_INET, SOCK_DGRAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = inet_addr(serverIP);
addr_len = sizeof(struct sockaddr);
printf("Sending data ... \n");
sendto(sock, send_data, strlen(send_data) 1, 0, (struct sockaddr*)&server_addr, addr_len);
printf("Receiving data ... \n");
bytes_read = recvfrom(sock, recv_data, 1024, 0, (struct sockaddr*)&client_addr, &addr_len);
printf("client received: %s\n", recv_data);
Server will listen for a message and then send response.
Client will send message and then listen for the response.
On the server side I am binding socket to INADDR_ANY and port 5000 while on the client side I am not binding socket at all.
If binding is not done on the server side server socket won't receive any message.
While on the other side even though socket binding is not done at all client socket will receive message sent by the server.
Why do I have to bind server socket but not client socket ?
CodePudding user response:
The first time the client socket send
s something the operating system automatically binds the socket to a random port. The client's port is received by the server, as the sender's port, and the server's response goes to the port the client socket was bound to.
On the server side you want to explicitly bind the socket to a specific, known port, first. Having the server socket bound to some random port won't be very helpful in having clients know where to find the server.