-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhappy.c
71 lines (58 loc) · 1.81 KB
/
happy.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
/* Simple connection using getaddrinfo(3), from the manpage;
* licensing terms for this function can be found at [0].
*
* [0] http://man7.org/linux/man-pages/man3/getaddrinfo.3.license.html
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include "rfc6555.h"
int connect_host(char *host, char *service) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s;
rfc6555_ctx *ctx;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(host,service, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
rfc6555_reorder(result);
ctx = rfc6555_context_create();
for (rp = result; rp != NULL; rp = rp->ai_next) {
fprintf(stderr, "connecting using rp %p (%s, af %d) ...",
rp,
rp->ai_canonname,
rp->ai_family);
sfd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (sfd == -1)
continue;
if ((sfd = rfc6555_connect(ctx, sfd, &rp)) != -1)
break; /* Success */
fprintf(stderr, " failed!\n");
perror("error: connecting: ");
}
rfc6555_context_destroy(ctx);
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "failed! (last attempt)\n");
perror("error: connecting: ");
return -3;
}
fprintf(stderr, " success!\n");
freeaddrinfo(result); /* No longer needed */
return sfd;
}