Linux下使用http协议下载文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h> //下载目标文件 : http://ftp.gnu.org/gnu/bc/bc-1.03.tar.gz
#define HOST_ADDR "ftp.gnu.org"
#define FILE_PATH "/gnu/bc/bc-1.03.tar.gz"
#define FILE_NAME "bc-1.03.tar.gz" void write_to_socket(int socketfd, const char* str)
{
write(socketfd, str, strlen(str));
} int main(void)
{
char* pstr = NULL;
int sk_fd = ;
int size = ;
int sum = ;
unsigned long filesize = ;
FILE* fp = NULL;
FILE* newfp = NULL;
struct sockaddr_in sk_addr;
struct hostent *phost = NULL;
char buf[] = {};
float processbar = 0.0f; // create TCP socket
sk_fd = socket(AF_INET, SOCK_STREAM, );
if (sk_fd < )
{
perror("socket failed");
exit();
} phost = gethostbyname(HOST_ADDR); memset(&sk_addr, 0x00, sizeof(sk_addr));
sk_addr.sin_family = AF_INET;
sk_addr.sin_port = htons();
sk_addr.sin_addr.s_addr = ((struct in_addr *)phost->h_addr)->s_addr;
if (connect(sk_fd, (struct sockaddr *)&sk_addr, sizeof(sk_addr)) < )
{
perror("connect failed");
close(sk_fd);
exit();
} write_to_socket(sk_fd, "GET "FILE_PATH" HTTP/1.1\r\n");
write_to_socket(sk_fd, "Accept: */*\r\n");
write_to_socket(sk_fd, "Host: "HOST_ADDR"\r\n");
write_to_socket(sk_fd, "Connection: Keep-Alive\r\n");
write_to_socket(sk_fd, "\r\n");
shutdown(sk_fd, SHUT_WR); fp = fdopen(sk_fd, "r");
newfp = fopen(FILE_NAME, "w+");
memset(buf, 0x00, sizeof(buf));
while (fgets(buf, , fp))
{
printf("%s\n", buf); if (filesize != ) /* find CRLF */
{
if ( == strlen(buf))
{
break;
}
}
else /* get file size */
{
pstr = strstr(buf, "Content-Length:");
if (pstr != NULL)
{
pstr = strchr(pstr, ':');
pstr++;
filesize = strtoul(pstr, NULL, );
printf("filesize = %lu\n", filesize);
}
}
memset(buf, 0x00, sizeof(buf));
} while ()
{
size = fread(buf, , , fp);
sum += size;
if ( == size)
{
break;
}
size = fwrite(buf, , size, newfp);
processbar = (float)sum / (float)filesize;
printf("%6d/%lu[%2.1f]\n", sum, filesize, processbar * );
}
fclose(fp);
fclose(newfp); return ;
}
上一篇:HCNA(华为)_DHCP篇


下一篇:UOJ22 UR #1外星人(动态规划)