使用socket 的api 来实现下载http 网络资源,其实整个流程也十分简单
1、解析url 得到域名 和 资源位置
2、根据域名得到服务器ip地址,然后通过ip 和端口建立socket连接
3、发送http 请求
4、解析http 响应
5、根据返回的响应内容,等到资源的大小,接收资源数据,保存到文件即可
需要引用到的头文件和一些常量的定义
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define HTTP_REQ_LENGTH 512
// http 请求头信息
static char http_header[] =
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Range: bytes=%d-\r\n"
"Connection: Close\r\n"
"Accept: */*\r\n"
"\r\n";
static char http_req_content[HTTP_REQ_LENGTH] = {0};
根据域名创建socket 连接的实现函数
static int create_request_socket(const char* host)
{
int sockfd;
struct hostent *server;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("[http_demo] create_request_socket create socket fail.\n");
return -1;
}
/* lookup the ip address */
server = gethostbyname(host);
if(server == NULL)
{
printf("[http_demo] create_request_socket gethostbyname fail.\n");
close(sockfd);
return -1;
}
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(80);
memcpy(&serv_addr.sin