-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.c
89 lines (71 loc) · 1.59 KB
/
net.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <net.h>
#include <log.h>
static int server = -1;
void listen_on(int port){
struct sockaddr_in addr;
int reuse_addr = 1;
server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(server == -1){
perror("socket");
exit(EXIT_FAILURE);
}
if(setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr))){
perror("setsockopt");
exit(EXIT_FAILURE);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(server, (struct sockaddr*)&addr, sizeof(addr)) == -1){
perror("bind");
close(server);
exit(EXIT_FAILURE);
}
if(listen(server, 10) == -1){
perror("listen");
close(server);
exit(EXIT_FAILURE);
}
}
void disconnect(int client){
write_log("disconnecting peer %d ... \n", client);
if(shutdown(client, SHUT_RDWR) == -1){
perror("shutdown");
exit(EXIT_FAILURE);
}
}
void net_close(){
if(server != -1){
close(server);
server = -1;
}
}
int get_server_fd(){
return server;
}
struct connection get_new_connection(){
struct connection conn;
int client;
/* TODO get address */
client = accept(server, NULL, NULL);
conn.fd = client;
strcpy(conn.addr, "unknown-address");
return conn;
}
int net_send(int fd, const char* data, size_t size){
int n = send(fd, data, size, 0);
if(n == -1){
fprintf(stderr, "net_send: %s\n", strerror(errno));
return -1;
}
else{
return n;
}
}