-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
93 lines (74 loc) · 2.01 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
//server - main.c
//DO NOT EDIT THIS; EDIT server.c INSTEAD
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netdb.h>
#include"server.h"
#include"utils.h"
static void sighandler(int sig) {
fprintf(stderr, "Received SIGINT\n");
exit(1);
}
int main(int argc, char* argv[], char* env[]) {
atexit(quit);
signal(SIGINT, sighandler);
struct addrinfo hints;
struct addrinfo *results;
struct addrinfo *rp;
int sfd;
int status;
//struct sockaddr_storage peer_addr;
//socklen_t peer_addr_len;
//ssize_t nread;
//char buf[ config.buf_size ];
char peer[NI_MAXHOST];
char service[NI_MAXSERV];
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; //ipv4 || ipv6
hints.ai_socktype = SOCK_STREAM; //tcp
hints.ai_flags = AI_PASSIVE; //wildcard IP address
hints.ai_protocol = 0; //any protocol
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
//construct host addr info
status = getaddrinfo(NULL, config.port, &hints, &results);
if( status ) {
fprintf(stderr, "ERROR getaddrinfo(): %s\n", gai_strerror(status));
exit(EXIT_FAILURE);
}
//iterate through socket types (ie: tcp ipv4, tcp ipv6) until successful bind
for(rp = results; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if( sfd == - 1) {
int errsv = errno;
fprintf(stderr, "WARNING socket(): %s\n", strerror(errsv));
continue;
}
if( bind(sfd, rp->ai_addr, rp->ai_addrlen)==0 ) {
break;
}
close(sfd);
}
//tie up loose ends
if( rp == NULL ) {
fprintf(stderr, "ERROR Failed to bind to socket\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(results);
//run init from server.c
init(argc, argv, env, sfd);
//server loop
for(;;) {
loop(argc, argv, env, sfd);
}
//in case there is a glitch in the matrix
close(sfd);
exit(EXIT_SUCCESS);
}