summaryrefslogtreecommitdiff
path: root/server.c
blob: 7288ecab5f14ea520ceeeff7b33e11f2420513e9 (plain)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
// 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(50037u),
        .sin_addr.s_addr = htonl(INADDR_ANY),
    };
    if (bind(fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
        perror("bind failed");
        return 1;
    }
    for (;;) {
        struct sockaddr_in source_address;
        char buffer[200];
        socklen_t source_address_len = sizeof(source_address);
        int const length = recvfrom(
                fd,
                buffer,
                sizeof(buffer) - 1,
                0,
                (struct sockaddr*)&source_address,
                &source_address_len);
        if (length < 0) {
            perror("recvfrom failed");
            break;
        }
        uint32_t const addr = ntohl(source_address.sin_addr.s_addr);
        uint8_t const a0 = addr >> 24;
        uint8_t const a1 = addr >> 16;
        uint8_t const a2 = addr >> 8;
        uint8_t const a3 = addr;
        printf("%d bytes: '%.*s' from %u.%u.%u.%u:%u\n",
                length, (int)length, buffer, a0, a1, a2, a3, source_address.sin_port);
    }
    close(fd);
}