I am just trying to make a UDP connection for the first time using C on linux. I have a server which is transmitting a number every second and I have a program which is receiving. The transmitter seems to be wroking but the receiver does not seem to be getting the messages. It just blocks on the recv function call.
Sender
int main(int argc, char** argv)
{
struct sockaddr_in addr;
int sfd, i;
sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bzero(&addr, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(32000);
for(i = 0; i < 1000; i++)
{
char buffer[100] = { 0 };
sprintf(buffer, "%d", i);
puts(buffer);
if(sendto(sfd, buffer, strlen(buffer), 0, (struct sockaddr*)&addr, sizeof(addr)) == -1)
{
perror("Send");
exit(1);
}
sleep(1);
}
close(sfd);
return 0;
}
Receiver
int main(int argc, char**argv)
{
int sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in addr;
perror("Socket");
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_port = htons(4000);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
char buffer[1000];
int n;
if(bind(sfd, &addr, sizeof(addr)) != 0)
{
perror("Bind");
exit(1);
}
while(1)
{
printf("Recv\n");
n = recv(sfd, buffer, 1000, 0);
printf("%d\n", n);
}
return 0;
}
Sender:
Receiver:
The port you send to has to be the port you receive on.