c - 在 Linux 上使用套接字发出 https 请求

标签 c linux sockets

如何在 Linux 上使用套接字发出 http 请求?目前,我得到了

HTTP/1.1 301 Moved Permanently
//etc
Location: https://server.com

这里是代码的相关部分(功能太大,不能贴在这里):

 /* Socket file descriptor. */
        int sock;
    struct sockaddr_in sockaddr;
    struct hostent *host; /* Host information. */
    sock = socket(AF_INET, /* IPV4 protocol. */
              SOCK_STREAM, /* TCP socket. */
              0); /* O for socket() function choose the correct protocol based on the socket type. */

    if(sock == INVALID_SOCKET) return SOCK_GENERROR;

    if((host = gethostbyname(server)) == NULL) {
        close(sock);
        return SOCK_HOSTNFOUND;
    }

    /* zero buffer */
    memset(&sockaddr, 0, sizeof(sockaddr));
    sockaddr.sin_family = AF_INET;
    memcpy(&sockaddr.sin_addr,
           host -> h_addr,
           host -> h_length );
    sockaddr.sin_port = htons(port);

    if(connect(sock, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) == INVALID_SOCKET) {
        close(sock);
        return SOCK_FERRCONN;
    }

    if(send(sock, sendbuf, bufsize, 0) == INVALID_SOCKET) {
        close(sock);
        return SOCK_FERRWRITE;
    }


       if((readed = recv(sock, recvbuffer, sizeof(recvbuffer), 0)) <= 0)
    break;

在调用中,server="server.com";port=80;

我试图从这段代码中尽可能地删除我的 onw 例程和类型,以使您更干净。

最佳答案

https 请求看起来就像 http 请求,但对客户端和服务器之间的实际通信进行了透明加密,并且在不同的默认端口上。好消息是透明加密允许您像编写常规 HTTP 客户端一样进行编程。坏消息是加密非常复杂,您需要一个专门的库来为您实现它。

一个这样的图书馆是OpenSSL .使用 OpenSSL,客户端的最小代码如下所示:

#include <openssl/ssl.h>

// first connect to the remote as usual, but use the port 443 instead of 80

// initialize OpenSSL - do this once and stash ssl_ctx in a global var
SSL_load_error_strings ();
SSL_library_init ();
SSL_CTX *ssl_ctx = SSL_CTX_new (SSLv23_client_method ());

// create an SSL connection and attach it to the socket
SSL *conn = SSL_new(ssl_ctx);
SSL_set_fd(conn, sock);

// perform the SSL/TLS handshake with the server - when on the
// server side, this would use SSL_accept()
int err = SSL_connect(conn);
if (err != 1)
   abort(); // handle error

// now proceed with HTTP traffic, using SSL_read instead of recv() and
// SSL_write instead of send(), and SSL_shutdown/SSL_free before close()

关于c - 在 Linux 上使用套接字发出 https 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255323/

相关文章:

sockets - Linux : Unix domain datagram sockets don't follow specification of connect/recv,吗?

c - SO_TIMESTAMP 套接字选项使用哪个时钟?

谁能告诉我下面的C代码的输出是什么?

c - 理解为什么我需要 malloc

c - 如何从内核板损坏报告中获取信息?

c++ - 我正在使用 MS Visual C++ Express 为 C++ 寻找一个简单的套接字接口(interface)

c++ - 在不使用预编译头文件的 C++ 项目中编译 C 文件?

c++ - 我想知道我们使用的ide是否包含链接器

c - 平台设备;为什么是 'alloc' 和 'add' ?

python - 如何在 python 中将 excel 自动化为 xml?