This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
100 lines (77 loc) · 2.32 KB
/
Copy pathmain.c
File metadata and controls
100 lines (77 loc) · 2.32 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
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include "handle.h"
#define PORT 9876
#define CONNECTION_BACKLOG 4
#define TRADEMARK_SYMBOL "\u2122"
int server_socket_fd;
struct sockaddr_in server_address;
int crash_error(char * message) {
printf("Error!\n");
printf("Message: %s\n", message);
exit(1);
return 1;
}
int main() {
int err;
printf("DynamicSystems" TRADEMARK_SYMBOL " link server\n");
// tell the kernel to clean up after our children
// we don't care about their exit statuses
signal(SIGCHLD, SIG_IGN);
// open a socket file descriptor
server_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket_fd == -1) {
return crash_error("Could not open socket!");
}
// set up our ip and port
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(PORT);
// set SO_REUSEADDR
uint32_t yes = 1;
if (setsockopt(server_socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(uint32_t)) == -1) {
return crash_error("Setting socket option failed!");
}
// bind to the socket
err = bind(server_socket_fd, (struct sockaddr *) &server_address, sizeof(server_address));
if (err == -1) {
return crash_error("Bind to socket failed!");
}
// listen to the socket
err = listen(server_socket_fd, CONNECTION_BACKLOG);
if (err == -1) {
return crash_error("Listen to socket failed!");
}
while (1) {
// accept a new connection
struct sockaddr_in client_address;
int client_address_length = sizeof(client_address);
int client_socket_fd = accept(server_socket_fd, (struct sockaddr *) &client_address, &client_address_length);
if (err == -1) {
return crash_error("Accepting connection failed!");
}
// fork ourselves to handle the new connection
int pid = fork();
if (pid < 0) {
return crash_error("Fork failed!");
}
if (pid == 0) {
// we're the client handler
// close the server socket since we don't need it
close(server_socket_fd);
// go to our processing code
int result = handle_connection(client_socket_fd, false);
return result;
}
// we're the main server
// close the client socket and continue with our day
close(client_socket_fd);
}
}