0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Cでシンプルなサーバを作る

Last updated at Posted at 2021-07-04

Kotlin Script でシンプルなサーバを作る をCでやってみました。

TCP の あるポートをリッスンして、 リクエストがあればテキスト(コンテンツ)を返します。

コード

ブラウザで http://localhost:49162 にアクセスするとページが表示されます。

#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

void handle_error(char* message) {
  perror(message);
  exit(EXIT_FAILURE);
}

int main(void) {
    int server_fd;

    // create socket file descriptor
    server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (server_fd == -1) handle_error("socket failed");

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(49162);
    int addr_len = sizeof(address);

    if (bind(server_fd,(struct sockaddr *) &address, sizeof(address)) < 0)
        handle_error("bind failed");

    // start to listen
    if (listen(server_fd, 3) < 0) handle_error("listen failed");

    printf("listening\n");

    while (1) {
        int client = accept(server_fd, (struct sockaddr *) &address, (socklen_t *)&addr_len);
        if (client < 0) handle_error("failed to accept connection.\n");

        char *body = "<!DOCTYPE html><html><head><title>Exemple</title></head><body><p>Server example.</p></body></html>";
        char *format = "HTTP/1.0 200 OK\r\n"
                "Date: Fri, 31 Dec 2021 23:59:59 GMT\r\n"
                "Server: Apache/0.8.4\r\n"
                "Content-Type: text/html\r\n"
                "Content-Length: %d\r\n"
                "Expires: Sat, 01 Jan 2020 00:59:59 GMT\r\n"
                "Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n"
                "\r\n"
                "%s";
        char message[4096];
        sprintf(message, format, strlen(body), body);

        // send the response
        send(client, message, strlen(message), 0);

        close(client);
    }

    close(server_fd);

    return EXIT_SUCCESS;
}

ブラウザでの表示結果

image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?