-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiServerExample.c.old
More file actions
89 lines (73 loc) · 2.76 KB
/
Copy pathapiServerExample.c.old
File metadata and controls
89 lines (73 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
/**
* This was the original code generated by ChatGPT for the sever. All other code was written by us, and the code below
* was modified to suit our needs. This old code is included as full transparency of what was generated with AI and to
* comply with the academic honesty policy.
*
* Prompt: "can you write a simple api endpoint in c that i can hit with netcat"
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
// Note - we did not include this method in our code.
void handle_api_request(int client_socket) {
const char* api_response = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"\r\n"
"Hello from the API endpoint!\n";
send(client_socket, api_response, strlen(api_response), 0);
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_address_len = sizeof(client_address);
char buffer[BUFFER_SIZE];
// Create socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// Initialize server_address structure
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
// Bind the socket
if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) == -1) {
perror("Socket binding failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_socket, 5) == -1) {
perror("Socket listening failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d...\n", PORT);
// Accept incoming connections
if ((client_socket = accept(server_socket, (struct sockaddr*)&client_address, &client_address_len)) == -1) {
perror("Connection acceptance failed");
exit(EXIT_FAILURE);
}
printf("Client connected: %s\n", inet_ntoa(client_address.sin_addr));
// Receive data from the client
ssize_t bytes_received;
while ((bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
buffer[bytes_received] = '\0'; // Null-terminate the received data
printf("Received from client:\n%s", buffer);
// Check if the request is for the API endpoint
if (strstr(buffer, "GET /api") != NULL) {
handle_api_request(client_socket);
break;
}
}
if (bytes_received == -1) {
perror("Error in receiving data");
exit(EXIT_FAILURE);
}
// Close the sockets
close(client_socket);
close(server_socket);
return 0;
}