- #include <winsock2.h>
- #include <windows.h>
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- char szServer[MAX_PATH] = "10.218.12.174";//"10.218.14.115";
- int nPort = 808;
- int main()
- {
- SOCKET sock = NULL;
- char szBuf[MAX_PATH] = {0};
- WSADATA wsaData = {0};
- sockaddr_in sin = {0};
- int nLen = 0;
- FILE* fp = NULL;
- if (0 != ::WSAStartup(0x0202, &wsaData))
- {
- cout << "init socket failed! err code = " << ::WSAGetLastError() << endl;
- return 0;
- }
- //创建socket
- if (INVALID_SOCKET == (sock = ::socket(AF_INET, SOCK_STREAM, 0)) )
- {
- cout << "创建socket失败! err code = " << ::WSAGetLastError() << endl;
- return 0;
- }
- sin.sin_family = AF_INET;
- sin.sin_port = ::htons(nPort);
- sin.sin_addr.S_un.S_addr = ::inet_addr(szServer);
- if (INADDR_NONE == sin.sin_addr.S_un.S_addr)
- {
- LPHOSTENT pHost = NULL;
- pHost = ::gethostbyname(szServer);
- if (NULL != pHost)
- {
- ::CopyMemory(&sin.sin_addr.S_un.S_addr, pHost->h_addr_list[0], pHost->h_length);
- }
- else
- {
- cout << "域名解析失败!" << endl;
- return 0;
- }
- }
- if (SOCKET_ERROR == ::connect(sock, (sockaddr*)&sin, sizeof(sin)) )
- {
- cout << "connect failed! err code = " << ::WSAGetLastError() << endl;
- return 0;
- }
- // 发送CONNCET请求令到代理服务器,用于和代理建立连接
- //代理服务器的地址和端口放在m_ProxyAddr,m_Port 里面
- sprintf(szBuf, "CONNECT %s:%d HTTP/1.1/r/nUser-Agent: MyApp/0.1/r/n/r/n", szServer, nPort);
- if (SOCKET_ERROR == ::send(sock, szBuf, strlen(szBuf), 0))
- {
- cout << "send message failed! err code = " << ::WSAGetLastError() << endl;
- return 0;
- }
- ::recv(sock, szBuf, MAX_PATH, 0);
- cout << "szBuf = " << szBuf << endl;
- //下载文件
- if (strstr(szBuf, "200") >= 0)
- {
- sprintf(szBuf, "GET http://blog.csdn.net/andylin02 HTTP/1.1/r/nHost:blog.csdn.net/r/nAccept: */*/r/n/r/n");
- if (SOCKET_ERROR == ::send(sock, szBuf, strlen(szBuf), 0))
- {
- cout << "send message failed! err code = " << ::WSAGetLastError() << endl;
- return 0;
- }
- fp = ::fopen("./save.txt", "w");
- if (NULL == fp)
- {
- cout << "打开文件失败!" << endl;
- return 0;
- }
- while (TRUE)
- {
- ::memset(szBuf, 0, MAX_PATH);
- nLen = ::recv(sock, szBuf, MAX_PATH - 1, 0);
- if (nLen == 0)
- {
- cout << "save success!" << endl;
- break;
- }
- ::fwrite(szBuf, nLen, 1, fp);
- ::fflush(fp);
- }
- }
- if (sock)
- {
- ::closesocket(sock);
- sock = NULL;
- }
- ::WSACleanup();
- return 0;
- }