-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitialize.c
More file actions
90 lines (76 loc) · 2.35 KB
/
initialize.c
File metadata and controls
90 lines (76 loc) · 2.35 KB
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
#include "networking.h"
#include "request.h"
#include "initialize.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int initialize_server(const char *hostname, const char *port,
char **buffer, int *serv_sockfd) {
if (bind_listen(hostname, port, serv_sockfd) != 0) {
return -1;
}
if (initialize_buffer(buffer) != 0) {
return -1;
}
return 0;
}
int bind_listen(const char *hostname, const char *port, int *serv_sockfd) {
struct addrinfo hints, *servinfo, *candidate;
int sockfd;
int value_true = 1;
int status;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(hostname, port, &hints, &servinfo);
if (status != 0) {
/* Fixed: was "/n" (literal slash-n) in the original. */
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return -1;
}
for (candidate = servinfo; candidate != NULL; candidate = candidate->ai_next) {
sockfd = socket(candidate->ai_family, candidate->ai_socktype,
candidate->ai_protocol);
if (sockfd == -1) {
perror("socket");
continue;
}
status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
&value_true, sizeof value_true);
if (status == -1) {
perror("setsockopt SO_REUSEADDR");
close(sockfd);
freeaddrinfo(servinfo);
return -1;
}
status = bind(sockfd, candidate->ai_addr, candidate->ai_addrlen);
if (status == -1) {
perror("bind");
close(sockfd);
continue;
}
break; /* Successfully bound. */
}
freeaddrinfo(servinfo);
if (candidate == NULL) {
/* Fixed: was "/n" (literal slash-n) in the original. */
fprintf(stderr, "Failed to bind to %s:%s\n", hostname, port);
return -1;
}
status = listen(sockfd, SOMAXCONN);
if (status == -1) {
perror("listen");
close(sockfd);
return -1;
}
*serv_sockfd = sockfd;
return 0;
}
int initialize_buffer(char **buffer) {
*buffer = (char *)malloc(BUFFER_SIZE);
if (*buffer == NULL) {
perror("malloc buffer");
return -1;
}
return 0;
}