-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.c
More file actions
91 lines (78 loc) · 2.76 KB
/
socket.c
File metadata and controls
91 lines (78 loc) · 2.76 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
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
WSADATA wsa;
SOCKET serverfd, newsocket;
struct sockaddr_in address;
char* html = "<html><body><h1>Hello there!</h1><button onclick=\"c();\">Click</button><script>function c(){alert('clicked');}</script></body></html>";
char http_response[BUFFER_SIZE] = "HTTP/1.1 200 OK\r\n";
char* content_length;
sprintf(content_length, "Content-Length: %d\r\n\r\n", (int) strlen(html));
strcat(http_response, "Content-Type: text/html\r\n");
strcat(http_response, content_length);
strcat(http_response, html);
// Required by Windows to start up a socket
int startup = WSAStartup(MAKEWORD(2, 2), &wsa);
if (startup != 0) {
fprintf(stderr, "Startup failed");
return 1;
}
serverfd = socket(AF_INET, SOCK_STREAM, 0);
if (serverfd == INVALID_SOCKET) {
fprintf(stderr, "Failed to create socket");
return 1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
int on_bind = bind(serverfd, (struct sockaddr *)&address, sizeof(address));
if (on_bind == SOCKET_ERROR) {
fprintf(stderr, "Failed to bind socket");
closesocket(serverfd);
WSACleanup();
return 1;
}
int on_listen = listen(serverfd, 3);
if (on_listen == SOCKET_ERROR) {
fprintf(stderr, "Failed to listen on socket");
closesocket(serverfd);
WSACleanup();
return 1;
}
printf("Server is now listening on port %d\n", PORT);
int addr_len = sizeof(address);
char buffer[BUFFER_SIZE] = {};
for (;;) {
newsocket = accept(serverfd, (struct sockaddr *)&address, &addr_len);
if (newsocket == INVALID_SOCKET) {
fprintf(stderr, "Failed to accept new socket\n");
continue;
}
printf("Incoming client connected.\n");
int received_bytes = recv(newsocket, buffer, BUFFER_SIZE - 1, 0);
if (received_bytes > 0) {
buffer[received_bytes] = '\0';
printf("Got request:\n%s\n", buffer);
int sent = send(newsocket, http_response, strlen(http_response), 0);
if (sent == SOCKET_ERROR) {
fprintf(stderr, "Failed to send response\n\n");
} else {
printf("Sent the response!\n\n");
}
} else if (received_bytes == 0) {
printf("Connection closed by a client.\n\n");
} else {
fprintf(stderr, "Failed to receive bytes\n\n");
}
closesocket(newsocket);
}
closesocket(serverfd);
WSACleanup();
return 0;
}