Created
March 14, 2012 14:25
-
-
Save mafice/2036823 to your computer and use it in GitHub Desktop.
a http client
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
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
bool http_request (const char* method, const char* path, | |
const char* hostname, unsigned short port); | |
int main (void){ | |
if(!http_request("GET", "/", "localhost", 80)){ | |
puts("an error ocourred :("); | |
exit(EXIT_FAILURE); | |
} | |
return EXIT_SUCCESS; | |
} | |
bool http_request (const char* method, const char* path, | |
const char* hostname, unsigned short port){ | |
int sock; | |
struct hostent* host; | |
struct sockaddr_in dst; | |
char* buf; | |
size_t bufsize; | |
if((buf = (char *) malloc(2000)) == NULL){ | |
return false; | |
} | |
memset(&dst, 0, sizeof(dst)); | |
dst.sin_family = AF_INET; | |
dst.sin_port = htons(port); | |
// get IP address | |
if((dst.sin_addr.s_addr = inet_addr(hostname)) == 0xffffffff){ | |
if((host = gethostbyname(hostname)) == NULL){ | |
return false; | |
} | |
memcpy(&dst.sin_addr, host->h_addr, host->h_length); | |
} | |
// create a socket | |
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ | |
return false; | |
} | |
// connect to the server | |
if(connect(sock, (struct sockaddr*) &dst, sizeof(dst)) == -1){ | |
return false; | |
} | |
// send request | |
sprintf(buf, "%s %s HTTP/1.1\r\n", method, path); | |
write(sock, buf, strlen(buf)); | |
sprintf(buf, "Host: %s\r\n", hostname); | |
write(sock, buf, strlen(buf)); | |
sprintf(buf, "Connection: close\r\n"); | |
write(sock, buf, strlen(buf)); | |
write(sock, "\r\n", sizeof("\r\n")); | |
// receive data | |
for(;;){ | |
int sz; | |
if((sz = read(sock, buf, 1000)) < 0) | |
break; | |
write(1, buf, sz); // Note: do not use printf | |
} | |
close(sock); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment