Re: download a file from a url in C++

Here's a C version.

PHP Code:


/*
*wget_sortof.c
*
*Copyright2007VyacheslavGoltser<slavikg@gmail.com>
*
*Thisprogramisfreesoftware;youcanredistributeitand/ormodify
*itunderthetermsoftheGNUGeneralPublicLicenseaspublishedby
*theFreeSoftwareFoundation;eitherversion2oftheLicense,or
*(atyouroption)anylaterversion.
*
*Thisprogramisdistributedinthehopethatitwillbeuseful,
*butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof
*MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.Seethe
*GNUGeneralPublicLicenseformoredetails.
*
*YoushouldhavereceivedacopyoftheGNUGeneralPublicLicense
*alongwiththisprogram;ifnot,writetotheFreeSoftware
*Foundation,Inc.,51FranklinStreet,FifthFloor,Boston,MA02110-1301,USA.
*/

/*getthemainpagefromgoogle.com*/

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

intmain(intargc,char**argv)
{
structsockaddr_inservaddr;
structhostent*hp;
intsock_id;
charmessage[1024*1024]={0};
intmsglen;
charrequest[]="GET/index.htmlHTTP/1.0\n"
"From:slava!!!\nUser-Agent:wget_sortofbyslava\n\n"
;

//Getasocket
if((sock_id=socket(AF_INET,SOCK_STREAM,0))==-1){
fprintf(stderr,"Couldn'tgetasocket.\n");exit(EXIT_FAILURE);
}
else{
fprintf(stderr,"Gotasocket.\n");
}

//bookusesbzerowhichmymanpagessayisdeprecated
//themanpagesaidtousememsetinstead.:-)
memset(&servaddr,0,sizeof(servaddr));

//getaddressforgoogle.com
if((hp=gethostbyname("google.com"))==NULL){
fprintf(stderr,"Couldn'tgetanaddress.\n");exit(EXIT_FAILURE);
}
else{
fprintf(stderr,"Gotanaddress.\n");
}

//bcopyisdeprecatedalso,usingmemcpyinstead
memcpy((char*)&servaddr.sin_addr.s_addr,(char*)hp->h_addr,hp->h_length);

//fillintportnumberandtype
servaddr.sin_port=htons(80);
servaddr.sin_family=AF_INET;

//maketheconnection
if(connect(sock_id,(structsockaddr*)&servaddr,sizeof(servaddr))!=0){
fprintf(stderr,"Couldn'tconnect.\n");
}
else{
fprintf(stderr,"Gotaconnection!!!\n");
}

//NOWTHEHTTPPART!!!

//sendtherequest
write(sock_id,request,strlen(request));

//readtheresponse
msglen=read(sock_id,message,1024*1024);

printf("responseis%dbyteslong\n",msglen);

//printthereasponse
printf("%s",message);

return0;
}




__________________

I am infallible, you should know that by now.

"My favorite language is call STAR. It's extremely concise. It has exactly one verb '*', which does exactly what I want at the moment." --Larry Wall

(02:15:31 PM) ***TimToady and snake oil go way back...

42 lines of Perl - SHI - Home Site

发表回复