|
-
November 21st, 2006, 02:08 PM
#1
Download a file using http & winsock
i'm trying to write a program that sends an http request to a server, and downloads a binary file. don't want to use wininet.dll functions b/c i'm already familiar with this method.
the program syntax will be:
httpget someserver.com /thefolder/thefile.zip c:\thefile.zip
i have not started the recv() part yet, b/c i am a bit confused on what to do next.
is my code ok so far?
here is what i have:
Code:
#include <string>
#include <stdio.h>
#include <winsock2.h>
using std::string;
int main(int argc, char **argv)
{
char buf[1024];
FillMemory(buf,1024,0x0);
string request;
int sendret;
int recvret;
const char lb[]="\x0a\x0d\x0a\x0d";
const char http[]="http\x3a//";
const char snsn[]="%s\n%s\n";
bool error1=false;
bool error2=false;
bool error3=false;
printf(snsn,lb,"-=[ httpget v1.0 by Avery Tarasov ]=-");
printf(snsn,"-=[ Email: [email protected] ]=-",lb);
if(argc!=4)
{
printf(snsn,"Correct usage: httpget server.com /folder/file.zip c:\\savehere.zip");
return 0;
}
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
printf(snsn,"Error initializing Winsock 2.2");
return 0;
}
error1=true;
if(LOBYTE(wsaData.wVersion)!=2||HIBYTE(wsaData.wVersion)!=2)
{
printf(snsn,"Winsock 2.2 not available");
goto cleanup;
}
struct hostent *h;
struct sockaddr_in sa;
SOCKET server1;
h=gethostbyname(argv[1]);
if(h==0)
{
printf(snsn,"gethostbyname() failed");
goto cleanup;
}
memcpy((char *)&sa.sin_addr,(char *)h->h_addr,sizeof(sa.sin_addr));
sa.sin_family=h->h_addrtype;
sa.sin_port=htons(80);
server1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(server1==INVALID_SOCKET)
{
printf(snsn,"socket() failed");
goto cleanup;
}
error1=false;
error2=true;
if(connect(server1,(struct sockaddr *)&sa,sizeof(sa))<0)
{
printf(snsn,"connect() failed");
goto cleanup;
}
request+="GET ";
request+=argv[1];
request+=argv[2];
request+=" HTTP/1.1";
request+=&lb[2];
request+="Host :";
request+=argv[1];
request+=lb;
sendret=send(server1,request.c_str(),request.length()+1,0);
if(sendret==-1)
{
printf(snsn,"send() failed");
goto cleanup;
}
//think i need recv and a new socket variable to use now.. stuck here a bit
cleanup:
if(error1)
{
WSACleanup();
}
if(error2)
{
WSACleanup();
closesocket(server1);
}
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|