-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.c
99 lines (76 loc) · 1.91 KB
/
main.c
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// SPDX-License-Identifier: GPL-3.0-or-later
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/timeb.h>
struct app_config {
char *host;
char *service;
};
int parse_argv(struct app_config *conf, int argc, char ** argv);
int connect_host(char *host, char *service);
void print_delta(struct timeb *start, struct timeb *stop);
int try_read(int sfd);
int main(int argc, char **argv) {
struct app_config conf;
int ret = 0;
int sfd = 0;
struct timeb start_all, start, stop;
if (0 != (ret = parse_argv(&conf, argc, argv))) {
fprintf(stderr, "error: parsing arguments: %d\n", ret);
fprintf(stderr, "usage: %s HOST PORT\n", argv[0]);
return ret;
}
fprintf(stderr, "happy-eyeballing %s:%s ... \n", conf.host, conf.service);
ftime(&start_all);
ftime(&start);
if((sfd = connect_host(conf.host, conf.service)) < 0)
{
fprintf(stderr, "error: connecting: %d\n", sfd);
return sfd;
}
ftime(&stop);
print_delta(&start, &stop);
fprintf(stderr, "reading ...\n");
ftime(&start);
if ((ret = try_read(sfd)) < 0) {
fprintf(stderr, "error: reading: %d\n", ret);
return ret;
}
ftime(&stop);
print_delta(&start, &stop);
print_delta(&start_all, &stop);
return ret;
}
int parse_argv(struct app_config *conf, int argc, char ** argv) {
if (argc < 3) {
return -1;
}
conf->host = strdup(argv[1]);
conf->service = strdup(argv[2]);
return 0;
}
void print_delta(struct timeb *start, struct timeb *stop) {
int startms, stopms;
startms = start->time*1000+start->millitm;
stopms = stop->time*1000+stop->millitm;
fprintf(stderr, "%dms\n", stopms - startms);
}
int try_read(int sfd) {
char buf[10];
ssize_t s;
while((s = read(sfd, buf, sizeof(buf))) < 0) {
if (EAGAIN != errno) {
perror("error: reading: ");
return -4;
}
}
fprintf(stderr, "read: ");
printf("%s\n", buf);
return 0;
}