-
Notifications
You must be signed in to change notification settings - Fork 2
/
utilities.c
47 lines (40 loc) · 1.06 KB
/
utilities.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
#include "utilities.h"
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int createAndBind(struct addrinfo *res, int isBind)
{
struct addrinfo *p;
int sockfd, yes = 1;
for(p = res; p != NULL; p = p->ai_next) {
if((sockfd = socket(p->ai_family,
p->ai_socktype, p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
}
int (*fncToUse)(int, const struct sockaddr*, socklen_t);
if (isBind)
fncToUse = &bind;
else
fncToUse = &connect;
if((*fncToUse)(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
if (!isBind)
close(sockfd);
perror("bind/connect failed");
continue;
}
break;
}
freeaddrinfo(res); // free the linked list
check(p == NULL, -1, "failed to find server and bind");
return sockfd;
}