C语言写的多线程下载器

1.软件介绍

qdown是一款开源的HTTP多线程下载软件。
特点:多线程,支持服务器重定向,支持断点续传。

平台:Solaris/FreeBSD/Windows(CygWin)

作者:小孙

2.如何使用

usage: qdown URL [thread_amount] [save as]
example: qdown http://www.baidu.com/img/logo.gif 5 /home/sunjoy/log.gif

3.如何编译
On Solaris: cc -lsocket -lnsl qdown.c
On FreeBSD: gcc -pthread qdown.c
或者用sunstudio打开工程文件编译

4.基本原理

4.1 多线程原理
HTTP协议规定在请求报头中加入Range: bytes=%d-%d (%d代表整数)来下载指定范围的块儿,
因此根据文件的总大小,qdown开启多个线程分别下载各个部分,最终完成下载整个文件。


4.2 服务器重定向
很多情况下,当客户端发起GET请求后,服务器可能通过Location: xxxxx来告诉客户端重定向
到新的URL,当qdown遇到这种情况时会去下载新的URL指定的文件。qdown最多允许5次重定向。


4.3 断点续传
由于程序被中断或者网络故障等原因可能导致一个文件没有下载完全。qdown在下载过程中会
维护一个.cfg文件来记录个线程的下载情况,当重新下载时,qdown会根据.cfg文件的记录从
上次断掉的地方开始下载。

5.改进方向
预计在下一版本中加入对FTP URL的支持

C代码 复制代码
  1. /**  
  2. ** description:qdown is a multithread downloader  
  3. ** author:Sunjoy  
  4. ** email:fxsjy @@@ yahoo.com.cn  
  5. ** from:ICT.CAS.  
  6. ** date:2007-9-10  
  7. **  
  8. */  
  9.   
  10. #include <stdio.h>   
  11. #include <stdlib.h>   
  12. #include <unistd.h>   
  13. #include <string.h>   
  14. #include <pthread.h>   
  15. #include <sys/types.h>   
  16. #include <sys/socket.h>   
  17. #include <netinet/in.h>   
  18. #include <arpa/inet.h>   
  19. #include <netdb.h>   
  20. #define MAX_THREAD 100   
  21.   
  22. typedef struct URLInfo   
  23. {   
  24.     char schema[8];   
  25.     char host[256];   
  26.     char host_name[256];   
  27.     unsigned int port;   
  28.     char file[256];   
  29. }URLInfo;   
  30.   
  31. typedef struct Connection   
  32. {   
  33.     int sock;   
  34.     URLInfo url_info;   
  35.     int avaliable;   
  36. }Connection;   
  37.   
  38. typedef struct Resource   
  39. {   
  40.     char file_url[256];   
  41.     int file_size;   
  42.     char file_name[256];   
  43. }Resource;   
  44.   
  45. typedef struct ThreadArg   
  46. {   
  47.     Resource* res;   
  48.     int start_pos;   
  49.     int limit;   
  50.     int no;   
  51. }ThreadArg;   
  52.   
  53. typedef struct BreakPoint   
  54. {   
  55.     int downloaded;   
  56.     int thread_amount;   
  57.     int tasks[MAX_THREAD][2];   
  58.        
  59. }BreakPoint;   
  60.   
  61. pthread_mutex_t g_mut;   
  62. int g_total=0;   
  63. int g_downloaded=0;   
  64. BreakPoint g_breakpoint;   
  65.   
  66. URLInfo parse_url(const char *url);   
  67. Connection open_url(const char * url);   
  68. Resource get_resource(const char *url);   
  69. void join_url(const char* old_url,const char* redirect,char * new_url);   
  70. void download(const char* url,int thread_amount,const char* file_name);   
  71. void* download_part(void* args);   
  72. void* monitor(void *args);   
  73. void store_breakpoint(char * cfgName);   
  74.   
  75. void store_breakpoint(char * cfgName)   
  76. {   
  77.     int z;   
  78.     FILE* f;   
  79.     f=fopen(cfgName,"w");   
  80.     fprintf(f,"%d/n",g_breakpoint.downloaded);   
  81.     fprintf(f,"%d/n",g_breakpoint.thread_amount);   
  82.     for(z=0;z<g_breakpoint.thread_amount;z++){   
  83.        fprintf(f,"%d-%d/n",g_breakpoint.tasks[z][0],g_breakpoint.tasks[z][1]);   
  84.     }   
  85.     fclose(f);   
  86. }   
  87.   
  88. void join_url(const char* old_url,const char* redirect,char * new_url)   
  89. {   
  90.     char stack1[256][256]={0},stack2[256][256]={0};   
  91.     int i=0,j=0,p1=0,p2=0;   
  92.     char seg[256]={0};   
  93.     URLInfo temp_urlinfo;   
  94.        
  95.     memset(new_url,0,sizeof(new_url));   
  96.     if(strstr(redirect,"://")!=NULL){   
  97.         strcpy(new_url,redirect);   
  98.     }   
  99.     else{   
  100.         while(1){   
  101.             while(redirect[i]!='/' && redirect[i]!=0){   
  102.                 seg[j++]=redirect[i++];   
  103.             }       
  104.             strcpy(stack1[p1++],seg);   
  105.             memset(seg,0,sizeof(seg));   
  106.             j=0;   
  107.             if(redirect[i]==0)   
  108.                 break;   
  109.             i++;   
  110.         }   
  111.         for(i=0;i<p1;i++){   
  112.             if(!strcmp(stack1[i],"..") && p2>-1)   
  113.                 p2--;   
  114.             else if(strcmp(stack1[i],".")){   
  115.                 strcpy(stack2[p2++],stack1[i]);   
  116.             }   
  117.         }   
  118.         //printf("##%s/n",stack2[0]);   
  119.       
  120.         if(!strcmp(stack2[0],"")){   
  121.             temp_urlinfo=parse_url(old_url);   
  122.             sprintf(new_url,"%s://%s:%d/",temp_urlinfo.schema,temp_urlinfo.host,temp_urlinfo.port);             
  123.         }   
  124.         else{   
  125.             i=strlen(old_url)-1;   
  126.             while(old_url[i]!='/')   
  127.                 i--;   
  128.             //printf("##%c/n",old_url[i]);   
  129.             strncpy(new_url,old_url,i+1);   
  130.             new_url[i+1]=0;   
  131.         }   
  132.         //printf("##%s/n",new_url);   
  133.         for(j=0;j<p2-1;j++){   
  134.             strcat(new_url,stack2[j]);   
  135.             strcat(new_url,"/");   
  136.         }   
  137.         strcat(new_url,stack2[p2-1]);   
  138.     }   
  139. }   
  140.   
  141. URLInfo parse_url(const char* url){   
  142.     int i=0,j=0;   
  143.     char schema[8]={0};   
  144.     char host[256]={0};   
  145.     char port[8]={0};   
  146.     char file[256]={0};   
  147.     char IP[32]={0};   
  148.     URLInfo url_info;   
  149.     struct hostent* hptr;   
  150.        
  151.     while(url[i]!=':'){   
  152.         schema[j++]=url[i++];   
  153.     }   
  154.   
  155.     for(i+=3,j=0;url[i]!=':' && url[i]!='/' && url[i]!=0;){   
  156.         host[j++]=url[i++];   
  157.     }   
  158.        
  159.     if(url[i]==':'){   
  160.         for(i+=1,j=0;url[i]!='/';){   
  161.             port[j++]=url[i++];   
  162.         }   
  163.         sscanf(port,"%d",&url_info.port);   
  164.     }   
  165.     else{   
  166.         url_info.port=80;   
  167.     }   
  168.        
  169.     if(url[i]!=0){   
  170.         for(j=0;url[i]!=0;){   
  171.             file[j++]=url[i++];   
  172.         }   
  173.     }   
  174.     else{   
  175.         file[0]='/';   
  176.     }   
  177.        
  178.     strcpy(url_info.schema,schema);   
  179.     strcpy(url_info.file,file);   
  180.     strcpy(url_info.host_name,host);   
  181.     hptr=gethostbyname(host);   
  182.       
  183.     if(hptr!=NULL){   
  184.         strcpy(url_info.host,   
  185.             inet_ntop(hptr->h_addrtype,*(hptr->h_addr_list),IP,sizeof(IP))   
  186.         );   
  187.     }   
  188.     //printf("%s/n",url_info.host);   
  189.     return url_info;   
  190. }   
  191. Connection open_url(const char* url){   
  192.     Connection conn;   
  193.     struct sockaddr_in remote_addr,local_addr;   
  194.   
  195.     conn.avaliable=0;   
  196.     conn.url_info=parse_url(url);   
  197.        
  198.     local_addr.sin_family=AF_INET;   
  199.     local_addr.sin_addr.s_addr=htonl(INADDR_ANY);   
  200.     local_addr.sin_port=htons(0);   
  201.     remote_addr.sin_family=AF_INET;   
  202.     remote_addr.sin_addr.s_addr=inet_addr(conn.url_info.host);   
  203.     remote_addr.sin_port=htons(conn.url_info.port);   
  204.        
  205.     conn.sock=socket(AF_INET,SOCK_STREAM,0);   
  206.     if(bind(conn.sock,   
  207.         (struct sockaddr*)&local_addr,   
  208.         sizeof(local_addr))<0){   
  209.             printf("bind error/n");   
  210.     }   
  211.        
  212.        
  213.        
  214.     if(conn.sock){   
  215.         if(   
  216.             connect(conn.sock,(struct sockaddr*)&remote_addr,sizeof(remote_addr))!=-1   
  217.         ){   
  218.             conn.avaliable=1;   
  219.         }   
  220.     }   
  221.        
  222.     return conn;   
  223. }   
  224.   
  225. Resource get_resource(const char* url){   
  226.     char pack[1024]={0};   
  227.     char buf[1024]={0};   
  228.     char redirect[256]={0},new_url[256]={0},old_url[256]={0};   
  229.     static int redirect_count=0;   
  230.     char* i;   
  231.     char* j;   
  232.     char* z;   
  233.     Resource res;   
  234.        
  235.     Connection conn=open_url(url);   
  236.     if(!conn.avaliable){   
  237.         return res;   
  238.     }   
  239.     sprintf(pack,"GET %s HTTP/1.1/nHost: %s/nAccept: */*/nReferer: http://%s/nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)/nPragma: no-cache/nCache-Control: no-cache/nConnection: close/n/n",conn.url_info.file,conn.url_info.host_name,conn.url_info.host_name);   
  240.     send(conn.sock,pack,strlen(pack),0);   
  241.     recv(conn.sock,buf,sizeof(buf),0);   
  242.     //printf("%s/n",buf);   
  243.     if(strstr(buf,"HTTP/1.1 404")!=NULL || strstr(buf,"HTTP/1.0 404")!=NULL){   
  244.        return res;   
  245.     }   
  246.     i=(char *)strstr(buf,"Location:");   
  247.     if(i!=NULL && redirect_count<5){   
  248.         sscanf(i,"Location: %s",redirect);   
  249.         sprintf(old_url,"%s://%s:%d%s",conn.url_info.schema,conn.url_info.host_name,conn.url_info.port,conn.url_info.file);   
  250.         join_url(old_url,redirect,new_url);   
  251.         //printf("@#%s/n",new_url);   
  252.         redirect_count++;   
  253.         return get_resource(new_url);   
  254.     }   
  255.     i=(char *)strstr(buf,"Content-Length:");   
  256.     if(i!=NULL){   
  257.         sscanf(i,"Content-Length: %d",&res.file_size);   
  258.     }   
  259.     strcpy(res.file_url,url);   
  260.     //printf("#%d/n",res.file_size);   
  261.     for(z=(char*)url;(j=strstr(z,"/"))!=NULL;){   
  262.         z=j+sizeof(char);   
  263.     }   
  264.     strcpy(res.file_name,z);   
  265.     close(conn.sock);   
  266.     return res;   
  267. }   
  268.   
  269. void* download_part(void * args)   
  270. {   
  271.     ThreadArg* targ=(ThreadArg*)args;   
  272.     Connection conn;   
  273.     FILE* f=NULL;   
  274.     char pack[1024]={0};   
  275.     char buf[1024]={0};   
  276.     int i=0,ct=0;   
  277.     char* body=NULL;   
  278.     //printf("%s,%d-%d/n",targ->res->file_url, targ->start_pos,targ->limit);   
  279.     conn=open_url(targ->res->file_url);   
  280.     while(!conn.avaliable){   
  281.         sleep(1);   
  282.         conn=open_url(targ->res->file_url);   
  283.     }   
  284.     if(conn.avaliable){   
  285.   
  286.         f=fopen(targ->res->file_name,"rb+");   
  287.         fseek(f,targ->start_pos,0);   
  288.         sprintf(pack,"GET %s HTTP/1.1/nHost: %s/nAccept: */*/nReferer: http://%s/nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)/nRange: bytes=%d-%d/nPragma: no-cache/nCache-Control: no-cache/n/n",conn.url_info.file,conn.url_info.host_name,conn.url_info.host_name,targ->start_pos,targ->start_pos+targ->limit-1);   
  289.         //printf("%s",pack);   
  290. begin_down:   
  291.         send(conn.sock,pack,strlen(pack),0);   
  292.         i=recv(conn.sock,buf,sizeof(buf),0);   
  293.            
  294.         if(strstr(buf,"HTTP/1.1 206")==NULL && strstr(buf,"HTTP/1.0 206")==NULL && strstr(buf,"HTTP/1.1 200")==NULL && strstr(buf,"HTTP/1.0 200")==NULL){   
  295.             sleep(2);   
  296.             memset(buf,0,sizeof(buf));   
  297.             conn=open_url(targ->res->file_url);   
  298.             goto begin_down;   
  299.         }   
  300.         //printf("##%s/n",body);   
  301.         body=strstr(buf,"/r/n/r/n")+4;   
  302.         if(body!=NULL){   
  303.             i=i-(body-buf);   
  304.             fwrite(body,sizeof(char),i,f);   
  305.             //printf("@@@@%x/n",buf);   
  306.             fflush(f);   
  307.             ct+=i;   
  308.             pthread_mutex_lock(&g_mut);   
  309.             g_downloaded+=i;   
  310.             pthread_mutex_unlock(&g_mut);   
  311.                
  312.             while(ct< targ->limit){   
  313.                 i=recv(conn.sock,buf,sizeof(buf),0);   
  314.                 if(i==0){   
  315.                     fclose(f);   
  316.                     conn.avaliable=0;   
  317.                     while(!conn.avaliable){   
  318.                         sleep(2);   
  319.                         //printf("waiting.../n");   
  320.                         conn=open_url(targ->res->file_url);   
  321.                     }   
  322.                     memset(pack,0,sizeof(pack));   
  323.                     memset(buf,0,sizeof(buf));   
  324.                     sprintf(pack,"GET %s HTTP/1.1/nHost: %s/nAccept: */*/nReferer: http://%s/nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)/nRange: bytes=%d-%d/nPragma: no-cache/nCache-Control: no-cache/n/n",conn.url_info.file,conn.url_info.host_name,conn.url_info.host_name,targ->start_pos+ct,targ->start_pos+targ->limit-1);   
  325.                     f=fopen(targ->res->file_name,"rb+");   
  326.                     fseek(f,targ->start_pos+ct,0);   
  327.                     goto begin_down;   
  328.                 }   
  329.                    
  330.                 fwrite(buf,sizeof(char),i,f);   
  331.                 fflush(f);   
  332.                 ct+=i;   
  333.                 pthread_mutex_lock(&g_mut);   
  334.                 g_downloaded+=i;   
  335.                 g_breakpoint.tasks[targ->no][0]=targ->start_pos+ct;   
  336.                 g_breakpoint.tasks[targ->no][1]=targ->limit-ct;   
  337.                 g_breakpoint.downloaded=g_downloaded;   
  338.                 pthread_mutex_unlock(&g_mut);   
  339.             }   
  340.             fclose(f);   
  341.             g_breakpoint.downloaded=g_downloaded;   
  342.             close(conn.sock);   
  343.         }   
  344.     }   
  345.     pthread_exit(NULL);   
  346. }   
  347. void* monitor(void* args){   
  348.     float p;   
  349.     int i,j,z,old;   
  350.     FILE* f;   
  351.     char cfgName[256];   
  352.     strcpy(cfgName,(char*)args);   
  353.     strcat(cfgName,".cfg");   
  354.        
  355.     while(1){   
  356.         p=g_downloaded/(g_total+0.0);   
  357.         if(g_downloaded>=g_total)   
  358.                 break;   
  359.         i=p*100/10;   
  360.         if(old!=g_downloaded){   
  361.                
  362.   
  363.             printf("/r");   
  364.             for(j=0;j<i;j++){   
  365.                 printf("==");   
  366.             }   
  367.             printf("%2.0f%%",p*100);   
  368.             fflush(stdout);   
  369.            
  370.             store_breakpoint(cfgName);   
  371.             old=g_downloaded;   
  372.         }   
  373.     }   
  374.     printf("/r====================100%%/n");   
  375.     remove(cfgName);   
  376.     pthread_exit(NULL);   
  377. }   
  378.   
  379.   
  380. void download(const char* url,int thread_amount,const char* file_name)   
  381. {   
  382.     ThreadArg targs[MAX_THREAD];   
  383.     pthread_attr_t * thAttr = NULL;   
  384.     pthread_t tids[MAX_THREAD],monitor_id,controler_id;   
  385.     Resource res;   
  386.     int i,block_size,t_start_pos,t_limit;   
  387.     FILE* f;   
  388.     char cfgName[256]={0};   
  389.        
  390.     if(thread_amount>MAX_THREAD)   
  391.         return;   
  392.     res=get_resource(url);   
  393.        
  394.     if(!strcmp(res.file_url,""))   
  395.         return;   
  396.        
  397.     if(strcmp(file_name,""))   
  398.         strcpy(res.file_name,file_name);   
  399.        
  400.     if(!strcmp(res.file_name,""))   
  401.         strcpy(res.file_name,"default_down");   
  402.        
  403.     if(res.file_size<1000000)   
  404.         thread_amount=1;   
  405.        
  406.     block_size=res.file_size/thread_amount;   
  407.     pthread_mutex_init(&g_mut,NULL);   
  408.        
  409.     strcpy(cfgName,res.file_name);   
  410.     strcat(cfgName,".cfg");   
  411.     printf("downloading %s,%d bytes... /n",res.file_name,res.file_size);   
  412.        
  413.     if(fopen(cfgName,"r")==NULL){   
  414. new_task:          
  415.         f=fopen(res.file_name,"wb");   
  416.         if(f==NULL){   
  417.             strcpy(res.file_name,"default_down");   
  418.             f=fopen(res.file_name,"wb");   
  419.         }   
  420.         fclose(f);   
  421.         g_total=res.file_size;   
  422.   
  423.         for(i=0;i<thread_amount;i++){   
  424.             targs[i].res=&res;   
  425.             targs[i].start_pos=block_size*i;   
  426.             targs[i].limit=block_size;   
  427.             if(i==thread_amount-1)   
  428.                 targs[i].limit+= (res.file_size%thread_amount);   
  429.                
  430.             targs[i].no=i;   
  431.             g_breakpoint.tasks[i][0]=targs[i].start_pos;   
  432.             g_breakpoint.tasks[i][1]=block_size;   
  433.             pthread_create(&tids[i], thAttr, download_part, (void *)&targs[i]);   
  434.         }   
  435.            
  436.     }   
  437.     else{   
  438.         f=fopen(cfgName,"r");   
  439.         if(fscanf(f,"%d",&g_downloaded)==-1)   
  440.             goto new_task;   
  441.         //printf("#%d/n",g_downloaded);   
  442.         g_total=res.file_size;   
  443.         fscanf(f,"%d",&thread_amount);   
  444.         for(i=0;i<thread_amount;i++){   
  445.             fscanf(f,"%d-%d",&t_start_pos,&t_limit);   
  446.             targs[i].res=&res;   
  447.             targs[i].start_pos=t_start_pos;   
  448.             targs[i].limit=t_limit;   
  449.             targs[i].no=i;   
  450.             g_breakpoint.tasks[i][0]=targs[i].start_pos;   
  451.             g_breakpoint.tasks[i][1]=t_limit;   
  452.             pthread_create(&tids[i], thAttr, download_part, (void *)&targs[i]);   
  453.         }   
  454.         fclose(f);   
  455.     }   
  456.        
  457.     pthread_create(&monitor_id,NULL,monitor,(void *)res.file_name);   
  458.     g_breakpoint.thread_amount=thread_amount;   
  459.     g_breakpoint.downloaded=g_downloaded;   
  460.     //printf("#%d/n",g_downloaded);   
  461.     /*for(i=0;i<thread_amount;i++){   
  462.         pthread_join(tids[i],NULL);   
  463.     }*/   
  464.   
  465.     pthread_join(monitor_id,NULL);   
  466. }   
  467.   
  468.   
  469.   
  470. int main (int ac, char * av[])   
  471. {   
  472.   int thread_amount=5;   
  473.   char file_name[256]={0};   
  474.   if(ac<2){   
  475.         printf("usage: qdown URL [thread_amount] [save as]/n");   
  476.         printf("example: qdown http://www.baidu.com/img/logo.gif 5 /home/sunjoy/log.gif/n");   
  477.   }   
  478.   else{   
  479.         if(ac>=3)   
  480.             sscanf(av[2],"%d",&thread_amount);   
  481.         if(ac>=4){   
  482.             strcpy(file_name,av[3]);   
  483.         }   
  484.         download(av[1],thread_amount,file_name);   
  485.            
  486.   }   
  487.      
  488.   return 0;   
  489. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值