//---------------------------------------------------------------------------

#pragma hdrstop
#include <winsock2.h>
#include <windows.h>
//---------------------------------------------------------------------------

#pragma argsused
unsigned char* pkcs7_blob; // блоб с запросом
unsigned long pkcs7_blob_size; // размер блоба
const char* host = "127.0.0.1"; // адрес CERTEX
const long port = 62280; // порт
int main(int argc, char* argv[])
{
	SOCKET my_sock;
	sockaddr_in dest_addr;
	HOSTENT *hst=NULL;
	unsigned char* responce=NULL;
	unsigned long responce_size=0;
	int iResult;
	DWORD wVersionRequested=0;
	WSADATA wsaData;
	int ret=0;
	try
	{
		 try
		 {
				 wVersionRequested = MAKEWORD(2, 2);
				 // открываем сокет и выполняем необходимые настройки
				 WSAStartup(wVersionRequested, &wsaData);
				 my_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
				 if (my_sock < 0) throw  WSAGetLastError();
				 int timeout = 1000;
				 if (setsockopt(my_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)))  throw  WSAGetLastError();
				 dest_addr.sin_family = AF_INET;
				 dest_addr.sin_port = htons(port);
				 if (inet_addr(host) != INADDR_NONE)
				 {
							 dest_addr.sin_addr.s_addr = inet_addr(host);
				 }
				 else
				 {
						if ((hst = gethostbyname(host))!=NULL)
						{

							 ((unsigned long *)&dest_addr.sin_addr)[0] =((unsigned long **)hst->h_addr_list)[0][0];
						}
						else
						{
								closesocket(my_sock);
								WSACleanup();
								throw E_INVALIDARG;
						}
				 }
				// выполняем соединение
				 if (connect(my_sock, (sockaddr *)&dest_addr, sizeof(dest_addr))) throw WSAGetLastError();
				 // посылаем запрос
				 int bb =  send (my_sock, pkcs7_blob , pkcs7_blob_size, 0);
				 if (bb==0) throw   WSAGetLastError();
				 if(shutdown(my_sock, SD_SEND) == SOCKET_ERROR) throw WSAGetLastError();
				 responce_size = 0;
				 iResult=0;
				 responce = (unsigned char*)malloc(16392);
				 // получаем ответ
				 memset(responce,0,sizeof(responce));
				 do
				 {
						if (responce_size+iResult>=16392) throw  WSAGetLastError();
						iResult = recv(my_sock, responce + responce_size,8196,0);
						if (iResult >= 0)
						{

								if (responce_size == 0)
										responce_size = iResult;
								else
										responce_size+= iResult;

						}
						else throw CRYPT_E_REVOCATION_OFFLINE;
				}
				while (iResult > 0);
				ret=0;
				// в переменной responce содержится ответ
		 }
		 catch(DWORD err)
		 {
				ret= err;
		 }
		 catch(int err)
		 {
				ret=err;
		 }
	}
	__finally
	{
			if (responce) free(responce);
			closesocket(my_sock);
			WSACleanup();
	}
	return ret;
}
//---------------------------------------------------------------------------
 