I have two functions in C that involve communication between a master and slave socket. The master sends a timestamp to the slave using the sendSyncMessage function, while the slave receives it using receiveSyncMessage. The master produces the correct output (e.g., "2023-12-07 11:07:03"), but the slave returns error code 10014.
The IP address for both master and slave is 127.0.0.1, port is 4455.
The master produces the correct output, but the slave returns error code 10014. I suspect there's an issue with how recvfromis used. Can someone help me identify and resolve the problem?
void sendSyncMessage(SOCKET clientSocket, struct sockaddr_in client_address)
{
SYSTEMTIME systemTime;
char buffer[1024];
GetLocalTime(&systemTime);
sprintf(buffer, "SYNC:%04d-%02d-%02d %02d:%02d:%02d", systemTime.wYear, systemTime.wMonth, systemTime.wDay,
systemTime.wHour, systemTime.wMinute, systemTime.wSecond);
printf("The current timestamp : %s\n", buffer);
sendto(clientSocket, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_address, sizeof(client_address));
}
void receiveSyncMessage(SOCKET server_socket)
{
struct sockaddr_in server_address;
int server_address_size = sizeof(server_address);
char buffer[1024];
int bytesReceived = recvfrom(server_socket, buffer, sizeof(buffer), 0, (struct sockaddr*)&server_address, server_address_size);
if (bytesReceived == SOCKET_ERROR) {
fprintf(stderr, "Receive failed: %ld\n", WSAGetLastError());
}
else{
buffer[bytesReceived] = '\0';
printf("Received Sync timestamp: %s\n", buffer);
printf("Bytes received: %d\n", bytesReceived);
}
}
In your
recvfromcall you are passingserver_address_size, but therecvfromfunction requires a pointer for that parameter. You should be passing&server_address_sizeto avoid the invalid pointer error (code 10014).Also, it appears you are using UDP, so I'm basing this part on that assumption: The server component will normally use an IP and a known port number (so that clients can find it). The clients will use an IP and port 0 -- allowing the system to assign a random, unused port number that will not conflict with existing sockets. Then the server will respond to the IP:Port it gets in the recvfrom() call when it receives a request from the client.
OTOH, if your server is just broadcasting a time sync network-wide, to a known port, then your server should use Port 0 and your clients (each on a different IP) would use the same known port the server is sending to.