C/C++实现HTTPS通信(抓取百度页面)

#include  

#include 
#include 

#include 
#include 

#pragma comment(lib,"libeay32.lib")
#pragma comment(lib,"ssleay32.lib")
#pragma comment(lib,"ws2_32.lib")


using namespace std;

int main()
{
	//加载SSL错误信息 
	SSL_load_error_strings();
	//添加SSL的加密/HASH算法 
	SSLeay_add_ssl_algorithms();
	//客户端,服务端选择SSLv23_server_method() 
	const SSL_METHOD *meth = SSLv23_client_method();
	//建立新的SSL上下文 
	SSL_CTX* ctx = SSL_CTX_new(meth);
	if(ctx == NULL)
	{
		ERR_print_errors_fp(stderr);
		cout<<"SSL_CTX_new error !";
		return -1;
	}
	
	WSADATA wsaData;
	if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
	{
		return -1;
	}
	SOCKET client = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(client == INVALID_SOCKET)
	{
		cout<<"socket error !";
		return -1;
	}
	
	string host = "www.baidu.com";
	unsigned short port = 443;
	hostent *ip = gethostbyname(host.c_str());
	
	sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);
	sin.sin_addr = *(in_addr*)ip->h_addr_list[0];
	
	if(connect(client,(sockaddr*)&sin,sizeof(sin)) == SOCKET_ERROR)
	{
		cout<<"connect error 1";
		return -1;
	}
	
	//建立SSL 
	int ret;
	SSL*ssl = SSL_new(ctx);
	if(ssl == NULL)
	{
		cout<<"SSL NEW error";
		return -1;
	}
	//将SSL与TCP SOCKET 连接 
	SSL_set_fd(ssl,client);
	//SSL连接 
	ret = SSL_connect(ssl);
	if(ret == -1)
	{
		cout<<"SSL ACCEPT error ";
		return -1;
	}
	
	stringstream stream;
	stream << "GET https://"<0)
	{
		start += ret;
	}
	rec[start] = 0;
	cout<

 

你可能感兴趣的:(OPENSSL,HTTPS)