summaryrefslogtreecommitdiffstats
path: root/03_exercise/srv/server.c
blob: 818036a262dbf61a1fb5ea436d5412fcb56e94c4 (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 9000

#define BUF_SIZE 256

static inline void die(const char *msg) {
    perror(msg);
    exit(-1);
}

int main() {
    struct sockaddr_in srv_addr, cli_addr;
    int       sockopt = 1;
    socklen_t sad_sz  = sizeof(struct sockaddr_in);
    int       sfd, cfd;
    ssize_t   bytes;
    char      in_buf[BUF_SIZE];
    char      out_buf[BUF_SIZE];

    srv_addr.sin_family      = AF_INET;
    srv_addr.sin_port        = htons(PORT);
    srv_addr.sin_addr.s_addr = INADDR_ANY;

    if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        die("Could not open socket");

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char *) &sockopt, sizeof(sockopt));

    if (bind(sfd, (struct sockaddr *) &srv_addr, sad_sz) < 0)
        die("Could not bind socket");

    if (listen(sfd, 1) < 0)
        die("Could not listen on socket");

    cfd = accept(sfd, (struct sockaddr *) &cli_addr, &sad_sz);
    if (cfd < 0)
        die("Could not accept incoming connection");

    printf("srv: connected: %s\n", inet_ntoa(cli_addr.sin_addr));

    while ((bytes = read(cfd, in_buf, BUF_SIZE)) != 0) {
        if (bytes < 0)
            die("Couldn't receive message");

        //printf("srv: %s\n", in_buf);

        if (strcmp(in_buf, "get") == 0) {
            // TODO: implement get
        } else if (strcmp(in_buf, "put") == 0) {
            // TODO: implement put
        } else if (strcmp(in_buf, "ping") == 0) {
            strncpy(out_buf, "pong!", sizeof(out_buf));
        } else {
            // TODO: connect our shell implementation
            memcpy(out_buf, "got: ", sizeof(out_buf));
            memcpy(out_buf + sizeof("got: ") - 1, in_buf, BUF_SIZE - sizeof("got: ") + 1);
        }

        if (write(cfd, out_buf, sizeof(out_buf)) < 0)
            die("Couldn't send message");

        memset(in_buf, 0, BUF_SIZE);
        memset(out_buf, 0, BUF_SIZE);
    }

    printf("srv: closing down\n");

    close(cfd);
    close(sfd);
}