#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <string.h>
char *http_header = "GET / HTTP/1.1\r\n"
"Host: www.idoushuo.com\r\n"
"Connection: keep-alive\r\ni"
"Accept: */*\r\n"
"Connection: close\r\n"
"\r\n";
char *hostname = "www.idoushuo.com";
int main(){
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
struct hostent *hp;
hp = gethostbyname(hostname);
memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
//send
send(sockfd, http_header, strlen(http_header), 0);
//recv
ssize_t length = 0;
char buf[101];
memset(buf, 0, sizeof(buf));
char *response = calloc(1, sizeof(char));
do{
length = recv(sockfd, buf, 100, 0);
if(length){
//leak mem
char *pp = realloc(response, strlen(response)+length+1);
if(!pp){
break;
}
response = pp;
memcpy(response + strlen(response), buf, length);
memset(buf, 0x0, sizeof(buf));
}
}while(length != 0);
printf("%s\n", response);
free(response);
}