Make an https request using sockets on linux

后端 未结 2 1853
我在风中等你
我在风中等你 2020-12-16 03:39

How do I make an http request using sockets on linux? currently, I\'m getting

HTTP/1.1 301 Moved Permanently
//etc
Location: https://server.com
相关标签:
2条回答
  • 2020-12-16 04:31

    https requests look just like http requests, but with transparent encryption of the actual communication between the client and the server, and on a different default port. The good news is that transparent encryption allows you to program just like you're writing a regular HTTP client. The bad news is that the encryption is complex enough that you need a specialized library to implement it for you.

    One such library is OpenSSL. Using OpenSSL, the minimal code for a client would look like this:

    #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()
    
    0 讨论(0)
  • 2020-12-16 04:33

    HTTPS is just like HTTP, but its encapsulated in a cryptographic SSL layer. You will need to use a lib like OpenSSL to make those HTTPS connections.

    OpenSSL will provide functions that replace the socket.h ones, to connect, read and write regular HTTP (or whatever other protocol you want to use) through a SSL channel, making the handling of the SSL part transparent to you.

    0 讨论(0)
提交回复
热议问题