原文地址:http://blog.csdn.net/huangxy10/article/details/8120106
//#include <Windows.h> #include <string> #include <iostream> #include <fstream> #include <vector> #include "winsock2.h" #include <time.h> #include <queue> #include <hash_set> #pragma comment(lib, "ws2_32.lib") using namespace std; #define DEFAULT_PAGE_BUF_SIZE 1048576 queue<string> hrefUrl; hash_set<string> visitedUrl; hash_set<string> visitedImg; int depth=0; int g_ImgCnt=1; //解析URL,解析出主机名,资源名 bool ParseURL( const string & url, string & host, string & resource){ if ( strlen(url.c_str()) > 2000 ) { return false; } const char * pos = strstr( url.c_str(), "http://" ); if( pos==NULL ) pos = url.c_str(); else pos += strlen("http://"); if( strstr( pos, "/")==0 ) return false; char pHost[100]; char pResource[2000]; sscanf( pos, "%[^/]%s", pHost, pResource ); host = pHost; resource = pResource; return true; } //使用Get请求,得到响应 bool GetHttpResponse( const string & url, char * &response, int &bytesRead ){ string host, resource; if(!ParseURL( url, host, resource )){ cout << "Can not parse the url"<<endl; return false; } //建立socket struct hostent * hp= gethostbyname( host.c_str() ); if( hp==NULL ){ cout<< "Can not find host address"<<endl; return false; } SOCKET sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP); if( sock == -1 || sock == -2 ){ cout << "Can not create sock."<<endl; return false; } //建立服务器地址 SOCKADDR_IN sa; sa.sin_family = AF_INET; sa.sin_port = htons( 80 ); //char addr[5]; //memcpy( addr, hp->h_addr, 4 ); //sa.sin_addr.s_addr = inet_addr(hp->h_addr); memcpy( &sa.sin_addr, hp->h_addr, 4 ); //建立连接 if( 0!= connect( sock, (SOCKADDR*)&sa, sizeof(sa) ) ){ cout << "Can not connect: "<< url <<endl; closesocket(sock); return false; }; //准备发送数据 string request = "GET " + resource + " HTTP/1.1 Host:" + host + " Connection:Close "; //发送数据 if( SOCKET_ERROR ==send( sock, request.c_str(), request.size(), 0 ) ){ cout << "send error" <<endl; closesocket( sock ); return false; } //接收数据 int m_nContentLength = DEFAULT_PAGE_BUF_SIZE; char *pageBuf = (char *)malloc(m_nContentLength); memset(pageBuf, 0, m_nContentLength); bytesRead = 0; int ret = 1; cout <<"Read: "; while(ret > 0){ ret = recv(sock, pageBuf + bytesRead, m_nContentLength - bytesRead, 0); if(ret > 0) { bytesRead += ret; } if( m_nContentLength - bytesRead<100){ cout << " Realloc memorry"<<endl; m_nContentLength *=2; pageBuf = (char*)realloc( pageBuf, m_nContentLength); //重新分配内存 } cout << ret <<" "; } cout <<endl; pageBuf[bytesRead] = '