Dev C++ Networking tutorial- Interaction with internet using Wininet

This article serves the purpose of internet addicts on creating their first desktop application written in c++ to connect International network (i.e. Internet). I learned this method just doing a simple research on one of the most popular library available with MinGW compiler i.e. Wininet (Provided by Microsoft to use it on Win OS). Beginners can use Devc++ as it has built in MinGW compiler or any IDE which supports MinGW Compiler (Recommended).

Let's be Practical,

  1. Create a new project with any name,
  2. Then create a c++ file named as "main.cpp",
  3. Include these library's as shown below in code.

"<cstring>" is optional, you can use it to define a variable to store web address.

Important Note:You can face a compilation error while compiling or debugging, So, Please make sure that you have linked your library with project in any IDE before compiling this script. You can check out the help section of particular IDE or Just go to the linker section of any IDE and Add the library which is located here: "C:\MinGW\lib\libwininet.a" (Default Location).

In Devc++, You can link via Project Menu -> compiler -> Then, Look at something specified with linker name. I Use Netbeans IDE and sometimes Codeblocks for my Projects, DevC++ is good for beginners (I used it too...).

#include<iostream>
#include<cstring>
#include<wininet.h>
Source

Now, create the main function followed by int and see the code below. This is the most basic code for connecting to internet via c++.

First, We declare a variable "connect" with datatype HINTERNET (Explained below) to store data (Tecnically named as 'handle') returned by InternetOpen() function. InternetOpen() does the basic work of checking and connecting network automatically via Windows Operating System.

Second, We declare another variable OpenAddress with same HINTERNET datatype to store data returned (Another handle) by InternetOpenUrl() Function while using the previous handle (data) returned by InternetOpen() - This function does the work of making a connection to address specified in it's argument.

We are using if statements or conditions in between the code to Check if functions and library is working properly or not. There is a GetLastError() Function in scond if statement that does the work of identifying and printing the error Number/code if our application failed to load a given Web-address. You can Learn more more about such errors here at official microsoft help center http://support.microsoft.com/kb/193625 .

#include<iostream>
#include<cstring>
#include<wininet.h>
using namespace std;
int main(){
HINTERNET connect = InternetOpen("MyBrowser",INTERNET_OPEN_TYPE_PRECONFIG,NULL, NULL, 0);

   if(!connect){
      cout<<"Connection Failed or Syntax error";
      return 0;
   }

HINTERNET OpenAddress = InternetOpenUrl(connect,"http://localhost/", NULL, 0, INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_KEEP_CONNECTION, 0);

   if ( !OpenAddress )
   {
      DWORD ErrorNum = GetLastError();
      cout<<"Failed to open URL \nError No: "<<ErrorNum;
      InternetCloseHandle(connect);
      return 0;
   }

   char DataReceived[4096];
   DWORD NumberOfBytesRead = 0;
   while(InternetReadFile(OpenAddress, DataReceived, 4096, &NumberOfBytesRead) && NumberOfBytesRead )
   {
           cout << DataReceived;
   }

   InternetCloseHandle(OpenAddress);
   InternetCloseHandle(connect);

   system("PAUSE");
}

Third, We declare two another variable DataReceived, NumberOfBytesRead for storing Data received via InternetReadFile() From Network (Internet). We are using while loop condition to continuously receive data till the size specified (4096) and Outputting it to console window via cout. Here, InternetReadFile() uses the data (Handle) returned by InternetOpenUrl() Function to receive data from a specified Location.

At Last, We are closing all the connections and destroying handles to successfully close application without causing any network problems via InternetCloseHandle(). system("PAUSE") Stops the screen from closing to display output to user, programmer or anyone who is interacting with application.

Basic Parts of code are explained here:

  1. HINTERNET, DWORD- Kind of Data Type to define variables similar to that of INT, Double, CHAR etc. , Just remember it.
  2. InternetOpen(), InternetOpenUrl(), GetLastError(), InternetReadFile(), InternetCloseHandle() - Functions defined in wininet library for clients to use it in their code to access internet.
  3. INTERNET_FLAG_PRAGMA_NOCACHE, INTERNET_FLAG_KEEP_CONNECTION, NULL, 0 - Are the default values of function attributes that can be used.
  4. system("PAUSE") - A built-in function of MinGW compiler to keep console window open to show output to programmer.
  5. Optional Tip - To convert Datatype string into const char*, you can do this way const char* variableName = StringVariable.c_str() as long as I remember.

You can Learn more about Wininet functions here at official microsoft Page - http://msdn.microsoft.com/en-us/library/aa385473(v=VS.85).aspx

Hope, Your Interest in c++ has now grown up little more...

My Quote : Programming may disclose most of the facts behind the working of real world as anything doesn't works itself.

More by this Author


Comments 12 comments

Krissie_59 5 years ago

Pretty picture :)


Hos 4 years ago

Very good.


Sumit 4 years ago

I want to write a client application which access webpages/urls in C++. Is winINet going to help in it? The app is to be a commandline app. It accesses some APIs on servers and gets data


itech profile image

itech 4 years ago from New Delhi, India Author

Yes, Wininet is a library provided by windows. So, application developed using this would run at least on windows.


Sumit 4 years ago

Do we have something similar on Linux available?


itech profile image

itech 4 years ago from New Delhi, India Author

Google has everything!!! U just need to about correct keyword in order to get exact results.


Martin 4 years ago

When I try to use this, i always get a char full of EndOfFile symbols. I use exactly the same code, the only change i've made is adding a pragma comment to wininet.lib and including windows.h. Could you guess, what could be the probleb by me? Thanks Martin


seigfried23 profile image

seigfried23 4 years ago

I'd love t use that picture of worldwide internet connectivity. Great hub - a bit too technical for me lol; but then that's my fault.


sidahmed 3 years ago

how i can make hacker account connect to internet


Poseidon 3 years ago

*giggle* I'm about to laugh. (The guy above)


3 years ago

Don't use Win API directly, save the time. Use the portable high-level frameworks instead like Boost.Asio (http://boost.org), C++ Network Library (http://cpp-netlib.org) or Unicomm (http://libunicomm.org). Stop using strcpy and etc. approach. ;)


UnWorld 10 days ago

Hello, this is a great tutorial. I have used this to successfully download files from the internet. There is one concern though. The downloaded file size is always bigger than the original because of the extra 4096 bytes completed at the end. Do you know how to fix this overflow problem?

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working