-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.c
79 lines (62 loc) · 2.17 KB
/
server.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
#include <sys/types.h>
#include <sys/socket.h> // listen()
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> // close()
#include <string.h> // memset()
#include <errno.h>
#include <stdio.h>
#include "server.h"
int create_tcp_server(const char* hostname, const char* servname)
{
int socket;
if ((socket = create_socket_stream(hostname, servname)) < 0)
return -1;
if (listen(socket, 5) < 0) { /* (Socket, Waiting list size) */
perror("listen");
close(socket);
return -1;
}
return socket;
}
int create_socket_stream(const char* hostname, const char* servname)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s;
memset(&hints, 0, sizeof(struct addrinfo)); /* init hints */
hints.ai_flags = AI_PASSIVE; /* Not only loopback if hostname is null */
hints.ai_family = AF_INET; /* AF_UNSPEC/AF_INET/AF_INET6 */
hints.ai_socktype = SOCK_STREAM; /* STREAM(TCP), DGRAM(UDP), SEQPACKET(?) */
hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
s = getaddrinfo(hostname, servname, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1) {
perror("socket");
continue;
}
int optvalue = 1;
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optvalue, sizeof(optvalue));
if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) {
break; /* Success */
} else {
fprintf(stderr, "Warning: failed to bind to address %s, service: %s (%m).\n", inet_ntoa(((const struct sockaddr_in*)(rp->ai_addr))->sin_addr), servname);
}
close(sfd);
}
freeaddrinfo(result); /* No longer needed */
if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Error: Could not bind\n");
return -1;
}
return sfd;
}