mmo-project/c/www/socket.c

64 lines
1.8 KiB
C
Raw Normal View History

2023-08-26 13:58:47 -04:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html>\r\n"
"<html lang='en'>\r\n"
"<head>\r\n"
"<style>body {background-color: black;color: #ddd;} </style>\r\n"
" <meta charset='UTF-8'>\r\n"
" <meta http-equiv='X-UA-Compatible' content='IE=edge'>\r\n"
" <meta name='viewport' content='width=device-width, initial-scale=1.0'>\r\n"
" <title>Document</title>\r\n"
"</head>\r\n"
"<body>\r\n"
" <h1>test</h1>\r\n"
"</body>\r\n"
"</html>";
int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0)
err(1, "can't open socket");
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *)&svr_addr, sizeof(svr_addr)) == -1)
{
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
while (1)
{
client_fd = accept(sock, (struct sockaddr *)&cli_addr, &sin_len);
printf("got connection\n");
if (client_fd == -1)
{
perror("Can't accept");
continue;
}
write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
shutdown(client_fd, SHUT_WR);
}
}