views:

1537

answers:

2

How can I make a program, like wget, such that the user can download files by typing the following?

$ wget http://www.testpage.com/file.pdf

And the program downloads the file. I want this syntax, my program name and the site, then the user press enter and my program start the file download.

Please if you are going to post the code, please post the full code, because I'm starting in C++ development.

+12  A: 

To practically build this from scratch, you need to read up on sockets: Windows Sockets 2 documentation.

But it's largely the same API on Unix or Linux also.

You're talking about writing an HTTP client, so you also need to refer to rfc2616.

You say you don't want a pre-written client to study - you want to write it yourself. So I'd better not say too much else.

But if you want to cheat a little, here are some hints.

Firstly, you should encapsulate socket handles in a class, called Socket. The class should have an int member to hold the socket handle. It should have private copy constructor and assignment, because it encapsulates a resource that cannot be shared easily between instances. And it should close the socket handle in its destructor.

Then you will probably benefit from making a simple data type to represent a parsed HTTP URL, so that's another class called HTTPUrl, which should have a constructor that takes a string and parses the URL into pieces.

Finally there would be an HTTPClient class that takes an HTTPUrl and opens a connection using those details, also an HTTP method (GET, POST, etc.) and can be given a payload and some headers to send, and can be asked to retrieve a payload back and headers back again. You could make it throw an exception if an error status is returned.

For extra credit, support https:// as well. Though I expect you'll draw the line at implementing SSL from scratch - investigate openSSL instead.

Daniel Earwicker
Thanks for the base!
Nathan Campos
If you want some comunication my e-mail is: [email protected] , if you want to talk with me by e-mail, please send me one and i put you in my contacts.
Nathan Campos
+1  A: 

If you only need it to work on Windows, take a look at URLDownloadToFile function. With less than 10 lines of code, you achieve the same functionality of wget.

Sherwood Hu