summaryrefslogtreecommitdiffstats
path: root/03_exercise/cli/client.c
blob: a98942de8183e9146dcd44c291d6b2f4e8edca01 (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
#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 HOST "127.0.0.1"

#define BUF_SIZE 256

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

int main() {
    struct sockaddr_in addr = {
            .sin_family = AF_INET,
            .sin_port = htons(PORT),
            .sin_addr.s_addr = inet_addr(HOST)
    };
    char buf[BUF_SIZE];
    int  cfd;

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

    if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) < 0)
        die("Could not connect to socket");

    char      *line = NULL;
    size_t    cap   = 0;
    __ssize_t length;

    while (1) {
        printf("%s > ", HOST);
        if ((length = getline(&line, &cap, stdin)) < 0) {
            fprintf(stderr, "Failed to read from STDIN");
            fflush(stderr);
            exit(-1);
        }

        if (strspn(line, " \n\t") == strlen(line)) {
            // skip empty lines - empty being just spaces or tabs
            continue;
        }

        line[length - 1] = '\0'; // cut the line feed

        if (strcmp(line, "exit") == 0) {
            break;
        }

        strncpy(buf, line, strlen(line));

        if (write(cfd, buf, BUF_SIZE) < 0)
            die("Could not send message");

        if (read(cfd, buf, BUF_SIZE) < 0)
            die("Could not receive message");

        printf("%s\n", buf);
        memset(buf, 0, BUF_SIZE);
    }

    close(cfd);
    return 0;
}