🚀

【C 言語】TCP クライアントで HTTP/1 リクエストを送信する

2024/10/18に公開

10年前に書いたコードが動くことを確認

client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

// https://en.wikibooks.org/wiki/C_Programming/Networking_in_UNIX
int main(void)
{
    int mysocket;
    struct timeval tv;
    struct sockaddr_in dest;
    uint8_t *msg;
    uint8_t *buf;
    size_t size;

    tv.tv_sec = 10;
    tv.tv_usec = 0;

    memset(&dest, 0, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    dest.sin_port = htons(5000);

    msg = (uint8_t *) malloc(1024);
    sprintf(msg,
      "GET / HTTP/1.1\r\n"
      "Host: localhost\r\n"
      "Connection: keep-alive\r\n"
      "\r\n"
    );

    buf = (uint8_t *) malloc(1024);

    mysocket = socket(AF_INET, SOCK_STREAM, 0);
    setsockopt(mysocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
    connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
    write(mysocket, msg, strlen(msg));
    size = read(mysocket, buf, 1024);
    close(mysocket);

    printf("%s", buf);

    return EXIT_SUCCESS;
}

Discussion