使用openssl實現乙個簡單的伺服器

2021-10-09 13:42:22 字數 2497 閱讀 4779

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define maxbuf 1024

#define server_cert_file "cert/servercert.pem"

#define server_key_file  "cert/serverkey.pem"

int main(int argc, char **ar**)

myport = atoi(ar**[i + 1]);}}

/* ssl 庫初始化 */

ssl_library_init();

/* 載入所有 ssl 演算法 */

openssl_add_all_algorithms();

/* 載入所有 ssl 錯誤訊息 */

ssl_load_error_strings();

/* 以 ssl v2 和 v3 標準相容方式產生乙個 ssl_ctx ,即 ssl content text */

/*ctx = ssl_ctx_new(sslv23_server_method());*/

ctx = ssl_ctx_new(sslv23_server_method());

/* 也可以用 sslv2_server_method() 或 sslv3_server_method() 單獨表示 v2 或 v3標準 */

if (ctx == null)

/* 載入使用者的數字證書, 此證書用來傳送給客戶端。 證書裡包含有公鑰 */

if (ssl_ctx_use_certificate_file(ctx, server_cert_file, ssl_filetype_pem) <= 0)

/* 載入使用者私鑰 */

if (ssl_ctx_use_privatekey_file(ctx, server_key_file, ssl_filetype_pem) <= 0)

/* 檢查使用者私鑰是否正確 */

if (!ssl_ctx_check_private_key(ctx))

/* 開啟乙個 socket 監聽 */

if ((sockfd = socket(af_inet, sock_stream, 0)) == -1) else

bzero(&my_addr, sizeof(my_addr));

my_addr.sin_family = af_inet;

my_addr.sin_port = htons(myport);

my_addr.sin_addr.s_addr = inaddr_any;

if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) else

if (listen(sockfd, 5) == -1) else

while (1) else

/* 基於 ctx 產生乙個新的 ssl */

ssl = ssl_new(ctx);

/* 將連線使用者的 socket 加入到 ssl */

ssl_set_fd(ssl, new_fd);

/* 建立 ssl 連線 */

if (ssl_accept(ssl) == -1)

/* 開始處理每個新連線上的資料收發 */

bzero(buf, maxbuf + 1);

strcpy(buf, "server->client");

/* 發訊息給客戶端 */

len = ssl_write(ssl, buf, strlen(buf));

if (len <= 0) else

bzero(buf, maxbuf + 1);

/* 接收客戶端的訊息 */

len = ssl_read(ssl, buf, maxbuf);

if (len > 0)

printf("recv from client: [%s],len: %d\n", buf, len);

else

printf("recv from client failed.\n");

/* 處理每個新連線上的資料收發結束 */

finish:

/* 關閉 ssl 連線 */

ssl_shutdown(ssl);

/* 釋放 ssl */

ssl_free(ssl);

/* 關閉 socket */

close(new_fd);

}/* 關閉監聽的 socket */

close(sockfd);

/* 釋放 ctx */

ssl_ctx_free(ctx);

return 0;

}

簡單實現乙個new

實現乙個new操作符 function mynew 測試 function person name var p2 mynew person,小明 console.log p2.name 解釋 1 let fn shift.call arguments 重點 slice內部實現是使用的this代表呼叫...

使用 Requests 實現乙個簡單網頁爬蟲

我們簡單介紹了爬蟲的基本原理,理解原理可以幫助我們更好的實現 python 提供了非常多工具去實現 http 請求,但第三方開源庫提供的功能更豐富,你無需從 socket 通訊開始寫,比如使用pyton內建模組 urllib 請求乙個 url 示例如下 import ssl from urllib....

使用selenium實現乙個簡單的爬蟲

使用selenium爬蟲 前2頁商品指定內容。主要思想 請求url,從原始碼中獲取指定selector,進行爬取。import time from selenium import webdriver browser webdriver.chrome browser.set page load tim...