This is a very basic question on UDP sockets. I myself have programmed some server/client application using them, but I'm stuck now and not able to see where the problem is.
I'm trying to do a server and a client which can both send and receive datagrams. So the server waits for a petition from the client on a determined socket, when it receives something through it, it sends its answer to the client. It works as far as the server getting the petition and sending answer back, but the client never gets it.
I show here some stripped code, just the basic part of the connection:
SERVER:
if ((socket_id = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
return;
}
bzero(&server_socket, sizeof(server_socket));
server_socket.sin_family = AF_INET;
server_socket.sin_addr.s_addr = INADDR_ANY;
server_socket.sin_port = htons(8724);
if (bind(socket_id, (struct sockaddr *) &server_socket, sizeof(server_socket)) == -1) {
return;
}
bzero(dgram_buffer, 1024);
client_socket_sz = sizeof(client_socket);
if((dgram_length = recvfrom(socket_id, dgram_buffer, 1024, 0, (struct sockaddr *) &client_socket, (socklen_t *) &client_socket_sz)) == -1) {
return;
}
if (sendto(socket_id, msg_buffer, offset, 0, (struct sockaddr *) &client_socket, (socklen_t) client_socket_sz) < 0) {
return;
}
printf("%s\n", msg_buffer);
CLIENT:
if ((socket_id = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
return;
}
if ((hostp = gethostbyname(hostname)) == 0) {
return;
}
bzero((char *) &client_socket, sizeof(client_socket));
client_socket.sin_family = AF_INET;
client_socket.sin_port = htons(8724);
bcopy(hostp->h_addr, (char *) &client_socket.sin_addr, hostp->h_length);
bzero(msg_buffer,sizeof(msg_buffer));
memcpy(msg_buffer,"mensaje\0",sizeof("message"));
socklen_t client_socket_len = sizeof(struct sockaddr_in);
if (sendto(socket_id, msg_buffer, sizeof(msg_buffer), 0, (struct sockaddr *) &client_socket, client_socket_len) < 0) {
return;
}
bzero(msg_buffer,sizeof(msg_buffer));
if(recvfrom(socket_id, msg_buffer, sizeof(msg_buffer), 0, (struct sockaddr *) &client_socket, &client_socket_len) == -1) {
return;
}
printf("%s\n", msg_buffer);
(I know that the buffers and their contents are not very well treated; I'm doing it correctly on my real application, I just typed that to get a quick test)
Could anyone give it a look and tell me if some setting is wrong? I've seen hundreds of examples on the net, reviewed old code of mine... to no avail. Maybe I've been on this for too many hours and I'm just skipping the obvious.
Thanks in advance.