-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.c
106 lines (80 loc) · 2.44 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 1337
void fatal(const char* msg);
void handle_client(int conn_fd, struct sockaddr_in* client_addr);
int start_server();
int main(void) {
int sock_fd = start_server();
printf("Pwnie wants connections on port %d\n", PORT);
for(;;) {
int conn_fd;
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(struct sockaddr);
if ((conn_fd = accept(sock_fd, (struct sockaddr*)&client_addr, &sin_size)) == -1)
fatal("accepting connection");
handle_client(conn_fd, &client_addr);
close(conn_fd);
}
return 0;
}
int start_server() {
int sock_fd;
socklen_t sin_size = sizeof(struct sockaddr);
if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
fatal("creating listening socket");
int yes = 1;
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
fatal("setting socket option");
struct sockaddr_in host_addr;
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT);
host_addr.sin_addr.s_addr = 0;
memset(&(host_addr.sin_zero), 0, 8);
if (bind(sock_fd, (struct sockaddr*)&host_addr, sin_size) == -1)
fatal("binding to socket");
if (listen(sock_fd, 5) == -1)
fatal("listening on socket");
return sock_fd;
}
void handle_client(int conn_fd, struct sockaddr_in* client_addr) {
printf("Connection from %s on port %d\n",
inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
const char* banner = "Here be pwnies!\n";
const int banner_len = strlen(banner);
send(conn_fd, banner, banner_len, 0);
// receive
char echo[512];
char* echo_ptr = echo;
char buff[256];
int recv_len = recv(conn_fd, &buff, 256, 0);
int nl = 0;
while (recv_len > 0) {
for (int i = 0; i < recv_len; ++i) {
if(buff[i] == '\n' || buff[i] == '\r') {
nl = 1;
recv_len = i;
break;
}
}
memcpy(echo_ptr, buff, recv_len);
echo_ptr += recv_len;
if (nl) break;
recv_len = recv(conn_fd, &buff, 256, 0);
}
const char* imp = ", in my pants!\n";
const int imp_len = strlen(imp);
memcpy(echo_ptr, imp, imp_len);
echo_ptr += imp_len;
*echo_ptr = '\0';
send(conn_fd, echo, echo_ptr - echo, 0);
}
void fatal(const char* msg) {
printf("Fatal error: %s\n", msg);
exit(1);
}