Files

86 lines
2.4 KiB
C
Raw Permalink Normal View History

2026-09-08 10:35:16 +08:00
#include "c_Socket.h"
#include <stdlib.h>
#include <stdio.h>
#include "c_AddrInfo.h"
#include "c_SockAddrUtil.h"
#include "c_SocketUtil.h"
int main(int argc, char** argv){
c_Socket_Init();
printf("Configuring local address...\n");
c_AddrInfo_t bindAddr;
c_AddrInfo_Init(&bindAddr, AF_INET, SOCK_STREAM, AI_PASSIVE, 0, "8080");
printf("Creating socket...\n");
c_socket_t socket_listen = c_SocketUtil_CreateFromAddrInfo(&bindAddr);
if (!c_Socket_IsValid(socket_listen)) {
fprintf(stderr, "socket() failed. (%d)\n", c_Socket_GetErrno());
return 1;
}
printf("Binding socket to local address...\n");
if (c_SocketUtil_BindWithAddrInfo(socket_listen, &bindAddr) !=C_ERR_OK) {
fprintf(stderr, "bind() failed. (%d)\n", c_Socket_GetErrno());
return 1;
}
c_AddrInfo_Destroy(&bindAddr);
printf("Listening...\n");
if (listen(socket_listen, 10) < 0) {
fprintf(stderr, "listen() failed. (%d)\n", c_Socket_GetErrno());
return 1;
}
printf("Waiting for connection...\n");
c_SockAddr_t client_address;
c_socket_t socket_client = c_SocketUtil_Accept(socket_listen, &client_address);
if (!c_Socket_IsValid(socket_client)) {
fprintf(stderr, "accept() failed. (%d)\n", c_Socket_GetErrno());
return 1;
}
printf("Client is connected... ");
char address_buffer[100];
c_SocketUtil_GetNameInfoForSockAddr(&client_address, address_buffer, sizeof(address_buffer), 0, 0);
printf("%s\n", address_buffer);
printf("Reading request...\n");
char request[1024];
int bytes_received = recv(socket_client, request, 1024, 0);
printf("Received %d bytes.\n", bytes_received);
printf("Sending response...\n");
const char *response =
"HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-Type: text/plain\r\n\r\n"
"Local time is: ";
int bytes_sent = send(socket_client, response, strlen(response), 0);
printf("Sent %d of %d bytes.\n", bytes_sent, (int)strlen(response));
time_t timer;
time(&timer);
char *time_msg = ctime(&timer);
bytes_sent = send(socket_client, time_msg, strlen(time_msg), 0);
printf("Sent %d of %d bytes.\n", bytes_sent, (int)strlen(time_msg));
printf("Closing connection...\n");
c_Socket_Close(socket_client);
printf("Closing listening socket...\n");
c_Socket_Close(socket_listen);
c_Socket_Destroy();
printf("Finished.\n");
return 0;
}