Hello all,
I am trying to make a program to get html code from a web site. I have this code which is partly taken from another example i found on the internet. My problem is that when i run the program it hangs... for 10 min. I just cancelled it after that.
Can anyone tell me why the program is hanging or if maybe something in my code is wrong?
Code:
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <string>
using namespace std;
int main()
{
WSADATA wsaData;
WORD version;
int error;
version = MAKEWORD(2, 0);
error = WSAStartup(version, &wsaData);
if(error != 0)
{
return FALSE;
}
if( LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0)
{
WSACleanup();
return FALSE;
}
cout << "Winsock initialized" << endl;
SOCKET client;
client = socket(AF_INET, SOCK_STREAM, 0);
if(client == INVALID_SOCKET)
{
cout << "Socket init failed" << endl;
fflush(stdin);
cin.get();
WSACleanup();
return FALSE;
}
sockaddr_in sockin;
sockin.sin_port = htons(80);
sockin.sin_addr.s_addr = inet_addr("216.239.136.165");
sockin.sin_family = AF_INET;
if(connect(client, (sockaddr*)&sockin, sizeof(sockin)) == SOCKET_ERROR)
{
cout << "Connection failed: " << WSAGetLastError();
fflush(stdin);
cin.get();
WSACleanup();
return FALSE;
}
else
{
cout << "Connection made to 216.239.136.165" << endl;
}
cout << "---------------------------" << endl;
char buffer[1024];
/*for(int i = 0; i < 1024; i++)
{
buffer[i] = '\0';
}*/
char welcome[] = "GET / HTTP/1.1\r\n";
strcat(welcome, "Host: asdf.com\r\n");
strcat(welcome, "Connection: close\r\n");
//strcat(welcome, "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5\r\n");
//strcat(welcome, "Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3\r\n");
//strcat(welcome, "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n");
//strcat(welcome, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3\r\n");
//strcat(welcome, "Referer: http://pozzyx.net/\r\n");
strcat(welcome, "\r\n");
cout << "Request:: " << endl << welcome << endl;
send(client, welcome, sizeof(welcome), 0);
string Source = "";
int i = 0;
do
{
i = recv(client, buffer, sizeof(buffer), 0);
Source += buffer;
}while (i != 0);
cout << Source << endl;
cout << endl << "Done." << endl;
WSACleanup();
fflush(stdin);
cin.get();
}