1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
// Initially based on https://stackoverflow.com/a/35570418
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
int const fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket failed");
return 1;
}
struct sockaddr_in const serveraddr = {
.sin_family = AF_INET,
.sin_port = htons(50037),
.sin_addr.s_addr = htonl(INADDR_ANY),
};
if (bind(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
perror("bind failed");
return 1;
}
for (;;) {
char buffer[200];
int const length = recvfrom(fd, buffer, sizeof(buffer) - 1, 0, NULL, 0);
if (length < 0) {
perror("recvfrom failed");
break;
}
buffer[length] = '\0';
printf("%d bytes: '%s'\n", length, buffer);
}
close(fd);
}
|