-
Notifications
You must be signed in to change notification settings - Fork 39
/
echoclient.c
68 lines (61 loc) · 1.59 KB
/
echoclient.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
static int open_connection(char *host, char *service);
int
main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "%s: error: wrong number of argument: %d for 2\n", argv[0], argc - 1);
fprintf(stderr, "Usage: %s HOST MESSAGE\n", argv[0]);
exit(1);
}
char *host = argv[1];
char *msg = argv[2];
int sock = open_connection(host, "echo");
FILE *f = fdopen(sock, "w+");
if (!f) {
perror("fdopen(3)");
exit(1);
}
fprintf(f, "%s\n", msg);
fflush(f);
char buf[1024];
fgets(buf, sizeof buf, f);
fclose(f);
fputs(buf, stdout);
exit(0);
}
static int
open_connection(char *host, char *service)
{
struct addrinfo hints, *res, *ai;
int err;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo(3): %s\n", gai_strerror(err));
exit(1);
}
for (ai = res; ai; ai = ai->ai_next) {
int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (sock < 0) {
continue;
}
if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
close(sock);
continue;
}
/* success */
freeaddrinfo(res);
return sock;
}
fprintf(stderr, "socket(2)/connect(2) failed");
freeaddrinfo(res);
exit(1);
}