c语言实现http请求
转载
1.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#include <errno.h>
int main(int argc, char **argv)
{
struct sockaddr_in server;
struct timeval timeout = {10, 0};
struct hostent *hp;
char ip[20] = {0};
char *hostname = "www.baidu.com";
int sockfd;
char message[1024];
int size_recv, total_size = 0;
int len;
char slen[32];
char chunk[512];
memset(message, 0x00, sizeof(message));
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
printf("could not create socket\n");
return -1;
}
if((hp=gethostbyname(hostname)) == NULL)
{
close(sockfd);
return -1;
}
strcpy(ip, inet_ntoa(*(struct in_addr *)hp->h_addr_list[0]));
printf("ip=%s\n", ip);
server.sin_addr.s_addr = inet_addr(ip);
server.sin_family = AF_INET;
server.sin_port = htons(80);
/*连接服务端*/
if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("connect error: %s", errno);
return 1;
}
/*http协议Get请求*/
strcpy(message, "GET /?ddd=eee HTTP/1.1\r\n");
strcat(message, "Host: www.baidu.com\r\n");
strcat(message, "Content-Type: text/html\r\n");
strcat(message,