Last active
July 26, 2016 02:08
-
-
Save 1995eaton/a5c61edf6a63b45ba34f to your computer and use it in GitHub Desktop.
Simple HTTP GET in C
This file contains 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
/* BUILD: gcc -lcrypto -lssl http_get.c -o http_get */ | |
/* USAGE: ./http_get www.google.com */ | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#define BUFFER_SIZE 1024 | |
int main(int argc, char *argv[]) { | |
struct addrinfo hints, *result, *rp; | |
char buffer[BUFFER_SIZE]; | |
int sfd; | |
memset(&hints, 0, sizeof(struct addrinfo)); | |
if (argc < 2) { | |
exit(1); | |
} | |
hints.ai_family = AF_UNSPEC; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = 0; | |
hints.ai_protocol = 0; | |
char host[1024], path[1024]; | |
char* has_slash = strchr(argv[1], '/'); | |
int idex = has_slash ? has_slash - argv[1] : -1; | |
if (idex != -1) { | |
strcat(path, argv[1] + idex + 1); | |
memcpy(host, argv[1], idex); | |
} else { | |
strcat(host, argv[1]); | |
} | |
if (getaddrinfo(host, "80", &hints, &result) != 0) { | |
printf("Error retrieving address information\n"); | |
exit(1); | |
} | |
for (rp = result; rp != NULL; rp = rp->ai_next) { | |
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
if (sfd == -1) { | |
continue; | |
} | |
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) { | |
break; | |
} | |
close(sfd); | |
} | |
if (rp == NULL) { | |
printf("Error connecting to host\n"); | |
exit(1); | |
} | |
freeaddrinfo(result); | |
char sendline[1024]; | |
sprintf(sendline, "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n", path, host); | |
write(sfd, sendline, strlen(sendline)); | |
memset(buffer, 0, BUFFER_SIZE); | |
while(read(sfd, buffer, BUFFER_SIZE - 1) != 0) { | |
printf("%s", buffer); | |
memset(buffer, 0, BUFFER_SIZE); | |
} | |
shutdown(sfd, SHUT_RDWR); | |
close(sfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment