0 Pluspunkte 0 Minuspunkte
Wie kann ich einen HTTP Get Request in C auf Linux erstellen?
bezieht sich auf eine Antwort auf: HTTP GET Request mit Domainname in C
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Hier ist ein einfaches Beispiel.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main() {

    const char *hostname = "example.com";
    const char *port = "80"; // HTTP-Port

    struct addrinfo hints, *res;
    int sockfd;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(hostname, port, &hints, &res) != 0) {
        fprintf(stderr, "getaddrinfo failed\n");
        return 1;
    }

    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

    if (sockfd == -1) {
        perror("Error creating socket");
        freeaddrinfo(res);
        return 1;
    }

    if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1) {
        perror("Error connecting to server");
        close(sockfd);
        freeaddrinfo(res);
        return 1;
    }

    const char *http_request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(sockfd, http_request, strlen(http_request), 0);

    char buffer[4096];
    ssize_t bytes_received;

    while ((bytes_received = recv(sockfd, buffer, sizeof(buffer) - 1, 0)) > 0) {
        buffer[bytes_received] = '\0';
        printf("%s", buffer);
    }

    if (bytes_received == -1) {
        perror("Error receiving data from server");
    }

    close(sockfd);
    freeaddrinfo(res);

    return 0;
}
von (732 Punkte)