Skip to content

Instantly share code, notes, and snippets.

@chomy
Created October 2, 2014 07:27
Show Gist options
  • Save chomy/1dcb7f9bb047ea5c961d to your computer and use it in GitHub Desktop.
Save chomy/1dcb7f9bb047ea5c961d to your computer and use it in GitHub Desktop.
HTTP Client in C
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#define GNU_SOURCE
#include <signal.h>
#include <poll.h>
int main(void)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd;
int s;
char buff[4];
int nread;
struct timespec timeout;
struct pollfd pfd;
const char *command = "GET / HTTP/1.0\n\n";
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
s = getaddrinfo("www.yahoo.co.jp", "http", &hints, &result);
if(s != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
return -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);
}
freeaddrinfo(result);
if(rp == NULL){
fprintf(stderr, "Connection Failer\n");
return -1;
}
send(sfd, command, strlen(command), 0);
timeout.tv_sec = 0;
timeout.tv_nsec= 100*1000*1000; /* 100ms */
pfd.fd = sfd;
pfd.events = POLLIN;
while(1){
ppoll(&pfd, 1, &timeout, NULL);
nread = recv(sfd, buff, sizeof(buff), 0);
if(nread == -1){
perror("read");
close(sfd);
return -1;
}
if(nread == 0)
break;
buff[nread] = '\0';
printf(buff);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment