I have an application written in C that is a server and a client at the same time. What I do is the following:
sock = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server, length);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(MYPORT);
char broadcast = '1';
int broadcastlen = sizeof(broadcast);
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, &broadcastlen) < 0) {
close(sock);
error("Error in setting broadcast option");
}
if (bind(sock, (struct sockaddr*) &server, sizeof(server)) < 0) {
close(sock);
error("Error in BINDING");
}
bzero(&sender, length);
bcast.sin_family = AF_INET;
bcast.sin_addr.s_addr = NBCAST; // NBCAST is the broadcast address of the subnet
bcast.sin_port = htons(MYPORT);
if (sendto(sock, dateQuery, strlen(dateQuery) + 1, 0, (struct sockaddr*)&bcast, sizeof(bcast)) < 0) {
close(sock);
error("ERROR in sending");
}
Up to this point everything works well. But I start a thread with the sock parameter to listen to, and do the following:
int len = sizeof(struct sockaddr_in);
struct sockaddr_in sender_addr;
recfrom(sock, recvbuff, recvbufflen, 0, (struct sockaddr*) &sender_addr, &len);
And it blocks there forever. I tried to make it work from different PCs, but it doesn’t seem to work, because the thread is blocked due to recvfrom(). Can anyone tell me what is wrong with my code?
Thanks
EDIT: if my code is broken, could you please suggest a way to solve this? So, my task is to implement an application in C that is a server and a client at the same time. I send a broadcast message every 3 seconds, and I have to answer to that broadcast message with the system time.
So far this is the idea I came up with, of course I did not answer to that broadcast message since I couldn’t even read it.
I just solved the problem. The code works perfectly, I just had to disable the firewall. But I don’t know exactly how did this help me. Any way, thanks for the answers and comments.