Created
November 25, 2023 15:27
-
-
Save EteimZ/beb84af6e0a27eaa9e49e89397f63994 to your computer and use it in GitHub Desktop.
A simple http client with C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <unistd.h> | |
| #include <arpa/inet.h> | |
| #define MAX_BUFFER_SIZE 1024 | |
| //Function prototypes: | |
| // function to send http request | |
| void send_http_request(int client_socket, const char *host, const char *path); | |
| // function to receive http response | |
| void receive_http_response(int client_socket); | |
| // main function | |
| int main(){ | |
| const char *host = "example.com"; | |
| const char *path = "/"; | |
| // Create a TCP/IP socket | |
| int client_socket = socket(AF_INET, SOCK_STREAM, 0); | |
| // check if socket connected succesfully | |
| if (client_socket == -1) { | |
| perror("Error creating socket"); | |
| exit(EXIT_FAILURE); | |
| } | |
| // Set up the server address | |
| struct sockaddr_in server_address; | |
| server_address.sin_family = AF_INET; | |
| server_address.sin_port = htons(80); | |
| inet_pton(AF_INET, host, &server_address.sin_addr); | |
| // Connect to the server | |
| if (connect(client_socket, (struct sockaddr*)&server_address, sizeof(server_address)) == -1) { | |
| perror("Error connecting to server"); | |
| close(client_socket); | |
| exit(EXIT_FAILURE); | |
| } | |
| // Send the HTTP request | |
| send_http_request(client_socket, host, path); | |
| // Receive and print the HTTP response | |
| receive_http_response(client_socket); | |
| // Close the socket | |
| close(client_socket); | |
| return 0; | |
| } | |
| void send_http_request(int client_socket, const char *host, const char *path){ | |
| // Create the HTTP request | |
| char request[MAX_BUFFER_SIZE]; | |
| snprintf(request, sizeof(request), "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", path, host); | |
| // send the HTTP request to the server | |
| write(client_socket, request, strlen(request)); | |
| } | |
| void receive_http_response(int client_socket){ | |
| // Recieve and print the HTTP response from the server | |
| char response[MAX_BUFFER_SIZE]; | |
| ssize_t bytes_received; | |
| // Read response streams | |
| while ((bytes_received = read(client_socket, response, sizeof(response) - 1)) > 0 ) { | |
| // Add string termination | |
| response[bytes_received] = '\0'; | |
| printf("%s", response); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment