#include <WinSock2.h> #include <iostream> #include <string.h> #include <errno.h> #include <stdlib.h>
#include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/pem.h> #include <openssl/crypto.h>
extern "C" { #include <openssl/applink.c> }
#pragma comment(lib, "WS2_32.lib") #pragma comment(lib,"libssl.lib") #pragma comment(lib,"libcrypto.lib")
#define MAXBUF 1024
char* GetFileName(char* Path) { if (strchr(Path, '\\')) { char ch = '\\'; char* ref = strrchr(Path, ch) + 1; return ref; } else { char ch = '/'; char* ref = strrchr(Path, ch) + 1; return ref; } }
void DownloadFile(SSL* ptr, const char* RootPath) { int FileSize = 0; char FilePath[1024] = { 0 }; char buffer[1024] = { 0 };
SSL_read(ptr, &FileSize, 4);
SSL_read(ptr, FilePath, 1024);
char* FileName = GetFileName(FilePath);
char sz[1024] = { 0 }; strcpy(sz, RootPath); strcat(sz, FileName); std::cout << sz << std::endl;
FILE* pointer = fopen(sz, "wb");
if (pointer != NULL) { DWORD length = 0; DWORD total_length = 0;
while ((length = SSL_read(ptr, buffer, 1024)) > 0) { if (fwrite(buffer, sizeof(char), length, pointer) < length) { break; }
total_length += length; memset(buffer, 0, 1024);
if (total_length >= FileSize) { std::cout << "[传输完成] " << total_length << std::endl; fclose(pointer); return; } } fclose(pointer); } }
int main(int argc, char** argv) { SOCKET sockfd, new_fd; struct sockaddr_in socket_ptr, their_addr; char buf[MAXBUF + 1]; SSL_CTX* ctx;
SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv23_server_method()); if (ctx == NULL) { return 0; }
if (SSL_CTX_use_certificate_file(ctx, "d://cacert.pem", SSL_FILETYPE_PEM) <= 0) { return 0; }
if (SSL_CTX_use_PrivateKey_file(ctx, "d://privkey.pem", SSL_FILETYPE_PEM) <= 0) { return 0; }
if (!SSL_CTX_check_private_key(ctx)) { return 0; }
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData); if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return 0; }
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { return 0; }
socket_ptr.sin_family = AF_INET; socket_ptr.sin_addr.s_addr = inet_addr("127.0.0.1"); socket_ptr.sin_port = htons(9999);
if (bind(sockfd, (struct sockaddr*)&socket_ptr, sizeof(struct sockaddr)) == -1) { return 0; } if (listen(sockfd, 10) == -1) { return 0; }
while (1) { SSL* ssl; int len = sizeof(struct sockaddr); if ((new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &len)) != -1) { printf("客户端地址: %s --> 端口: %d --> 套接字: %d \n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd); }
ssl = SSL_new(ctx); SSL_set_fd(ssl, new_fd); if (SSL_accept(ssl) == -1) { closesocket(new_fd); break; }
DownloadFile(ssl, "d://lyshark/");
finish: SSL_shutdown(ssl); SSL_free(ssl); closesocket(new_fd); }
closesocket(sockfd); WSACleanup(); SSL_CTX_free(ctx);
system("pause"); return 0; }
|