summaryrefslogtreecommitdiff
path: root/client.c
blob: 7c0eb717e166b374ce779f585323cfa255288379 (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
50
51
52
53
54
55
56
57
58
#define _GNU_SOURCE  // getline
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include "icmpd.h"
#include "util.h"

int main(void) {
	const char *remote_addr = "127.0.0.1";
	// const char *remote_addr = "198.211.118.67";
	struct icmpd *d = icmpd_create_client(inet_addr(remote_addr));
	int d_fd = icmpd_get_select_fd(d);

	while (true) {
		fd_set inset;
		FD_ZERO(&inset);
		FD_SET(0, &inset);
		FD_SET(d_fd, &inset);

		int ret = select(d_fd + 1, &inset, NULL, NULL, NULL);
		if (ret < 0) {
			if (errno == EINTR) continue;
			perror("select");
			return 1;
		}

		if (ret == 0) continue;  // timeout

		if (FD_ISSET(0, &inset)) {
			char *line = NULL;
			size_t linelen = 0;
			errno = 0;
			ssize_t nr = getline(&line, &linelen, stdin);
			if (nr < 0) {
				if (errno == 0) break;  // EOF
				perror("getline");
				exit(1);
			}
			if (nr > 0) nr--;
			icmpd_send(d, line, nr);
			free(line);
		}

		if (FD_ISSET(d_fd, &inset) && icmpd_peek(d)) {
			struct icmpd_received msg = icmpd_recv(d);
			printf("Recv: %zu\n", msg.length);
			xxd(stdout, msg.data, msg.length);
		}
	}
}