我正在尝试建立安全(https)连接。在我的示例代码中,我试图通过端口443连接到www.yahoo.com。 虽然建立了连接并且我能够发送HTTP CONNECT请求,但是来自服务器的响应是winsock错误10054。 我不确定我做错了什么。 任何帮助将不胜感激。
// HttpsTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <WinSock2.h>
#define BUFFFER_SIZE 1024*1024
#define MESSAGE "CONNECT www.yahoo.com:443 HTTP/1.0\
User - Agent : Mozilla / 5.0 (Windows NT 6.1; WOW64; Trident / 7.0; rv:11.0) like Gecko\
Host : www.yahoo.com\
Content - Length : 0\
DNT : 1\
Proxy - Connection : Keep - Alive\
Pragma : no - cache"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2); //0x202
int wsaError = ::WSAStartup(wVersionRequested, &wsaData);
char *pBuffer = MESSAGE;
string server_name("www.yahoo.com");
int retval, Len;
unsigned int addr;
int socket_type = SOCK_STREAM;
struct sockaddr_in server;
struct hostent *hp = NULL;
DWORD dwPort = 443;
hp = gethostbyname(server_name.c_str());
if (hp == NULL)
{
wsaError = ::WSAGetLastError();
}
memset(&server, 0, sizeof(server));
memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(static_cast<u_short>(dwPort));
SOCKET connToServer = socket(AF_INET, socket_type, IPPROTO_TCP); /* Open a socket */
if (connToServer != INVALID_SOCKET)
{
if (connect(connToServer, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR)
{
wsaError = ::WSAGetLastError();
}
}
Len = strlen(pBuffer);
retval = send(connToServer, pBuffer, Len, 0);
if (retval == SOCKET_ERROR)
{
wsaError = ::WSAGetLastError();
}
vector<char> vecBuffer(BUFFFER_SIZE, 0);
retval = recv(connToServer, vecBuffer.data(), static_cast<int>(vecBuffer.capacity()) - 1, 0);
if (retval == SOCKET_ERROR)
{
wsaError = ::WSAGetLastError(); // Always get a 10054.
}
return 0;
}