Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created August 27, 2013 06:54
Show Gist options
  • Save martintrojer/6350410 to your computer and use it in GitHub Desktop.
Save martintrojer/6350410 to your computer and use it in GitHub Desktop.
download stuff on windows
// This has more chance passing thorugh a (windows) firewall / proxy setup than anything else.
// Downloads files like IE would.
#include <stdio.h>
#include <iostream>
#include "windows.h"
#include "wininet.h"
int main(int argc, char* argv[])
{
if (argc != 3) {
std::cerr << "Usage; iedl URL OUTFILENAME" << std::endl;
return -1;
}
char* url = argv[1];
char *filename = argv[2];
HINSTANCE h = LoadLibrary("wininet.dll");
if (!h) {
std::cerr << "Can't load wininet.dll" << std::endl;
return -1;
}
InternetAttemptConnect(0);
HINTERNET internet = InternetOpen("IEDL", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
DWORD flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE;
HINTERNET connection = InternetOpenUrl(internet, url, NULL, 0, flags, 0);
if (connection == NULL) {
std::cerr << "Error making connection with: " << url << std::endl;
return -1;
}
HttpSendRequest(connection, 0, 0, 0, 0);
DWORD type, type_s;
type_s = sizeof(type);
InternetQueryOption (connection, INTERNET_OPTION_HANDLE_TYPE,
&type, &type_s);
switch (type)
{
case INTERNET_HANDLE_TYPE_HTTP_REQUEST:
case INTERNET_HANDLE_TYPE_CONNECT_HTTP:
type_s = sizeof (DWORD);
if (HttpQueryInfo (connection,
HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
&type, &type_s, NULL)) {
if (type == 401) {
std::cerr << type << " Authorization required" << std::endl;
InternetCloseHandle(connection);
return -1;
}
else if (type == 407) {
std::cerr << type << " Proxy authorization required" << std::endl;
InternetCloseHandle(connection);
return -1;
}
else if (type >= 300) {
std::cerr << type << " Error" << std::endl;
InternetCloseHandle(connection);
return -1;
}
}
default:
std::cout << type << " Conncetion OK" << std::endl;
}
FILE* fp = fopen(filename,"wb");
if (fp == NULL) {
std::cerr << "Error opening file" << filename << std::endl;
InternetCloseHandle(connection);
return -1;
}
DWORD actual = 0;
char buf[1024];
int ctr = 0;
do {
InternetReadFile(connection, buf, 1024, &actual);
// std::cout << "Read " << actual << " byte(s)" << std::endl;
ctr += actual;
std::cout << "." ;;
fwrite(buf, sizeof(char), actual, fp);
} while (actual > 0);
std::cout << "Read " << ctr << " bytes"<< std::endl;
fclose(fp);
InternetCloseHandle(connection);
}
all: iedl.exe
iedl.exe: iedl.cpp
g++ -g iedl.cpp -o iedl.exe -l wininet
clean:
rm -rf iedl.exe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment