#include<unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include<sys/stat.h> #include<fcntl.h> #include <sys/socket.h>
#define PORT 80 #define MAXDATASIZE 100
int main(int argc, char *argv[]) { int sockfd, numbytes; struct hostent *he; struct sockaddr_in their_addr; int fd, size, length = 0, bufsize; char buf[1024], *p; char get_str[] = "GET /~jianfeng/adsl/Linux_ADSL.html HTTP/1.1\r\nAccept: */*\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon)\r\nHost: 135.1.218.129\r\nConnection: Keep-Alive\r\n\r\n";
if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) { perror("socket"); exit(1); }
their_addr.sin_family = AF_INET; their_addr.sin_port = htons(PORT); their_addr.sin_addr.s_addr = inet_addr("135.1.218.129"); bzero(&(their_addr.sin_zero), 8);
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } if ( send(sockfd, get_str, sizeof(get_str), 0) < 0 ) { perror("send to ihgpweb failed"); exit(1); }
recv(sockfd,buf,sizeof(buf),0);
/* check if server return 200 0K */ printf("%s\n", buf); if ( strstr(buf, "HTTP/1.1 200 OK") != NULL ) { /* get the file length */ p = strstr(buf, "Content-length: "); p += 16; while ( *p !='\r' ) { length = length*10 + *p - '0'; p++; } printf("file length: %d\n", length);
fd = open("Linux_ADSL.html",O_WRONLY|O_CREAT); while ( length > 0 ) { if ( length > 1024 ) bufsize = 1024; else bufsize = length;
size = read(sockfd,buf,1024); printf("==========%d\n", size); write(fd, buf, size); length = length - size; }
printf("file download complete\n"); close(fd);
} close(sockfd); return 0; }
|