title: How to make an https request in c?
body: <p>I have been trying to make an https request in c using openssl. However for some reason openssl gives me an segmentation fault. I am not sure what exactly is going on, but SSL_read and SSL_free give me a segmentation fault.</p>
  
  <p>I have setup a struct to work a bit like a class, that holds all the information about the connection.</p>
  
  <p><strong>https.h</strong></p>
  
  <pre><code>struct sock {
    char ip[20];
    int socket;
    char lastcmd[1024];
    int loop;
    SSL *conn;
    int port;
  };
  
  
  int connect_sock(struct sock s) {
      s.socket = socket(AF_INET,SOCK_STREAM,0);
      if(s.socket == -1) {
          return 0;
      }
      struct sockaddr_in server;
      server.sin_addr.s_addr = inet_addr(s.ip);
      server.sin_family = AF_INET;
      server.sin_port = htons( s.port );
      if (connect(s.socket , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
      {
          return 0;
      }
      SSL_load_error_strings ();
      SSL_library_init ();
      SSL_CTX *ssl_ctx; = SSL_CTX_new (SSLv23_client_method ());
      s.conn = SSL_new(ssl_ctx);
      SSL_set_fd(s.conn, s.socket);
      return 1;
  }
  
  int read_sock(struct sock s,size_t length) {
      s.lastcmd[length*2];
      if(SSL_read(s.conn, s.lastcmd,length) &lt;0) {
          return 0;
      }
      return 1;
  }
  
  void close_sock(struct sock s) {
      SSL_shutdown(s.conn);
      close(s.socket);
  }
  </code></pre>
  
  <p>I call upon the above code like this</p>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>int main() {
      struct sock s;
      hostname_to_ip("www.google.com",s.ip);
      printf("%s\n",s.ip);
      s.port = 443;
      if(connect_sock(s)==1) {
          printf("Connected to %s\n",s.ip);
          read_sock(s,1024);
          printf("%s\n",s.lastcmd);
          close_sock(s);
      }
  }
  </code></pre>
  
  <p>So the output is like this</p>
  
  <pre><code>ip.ip.ip.ip
  Connected to ip.ip.ip.ip
  Segmentation fault (core dumped)
  </code></pre>
  
  <p>Although the main.c given above attempts to read when it produces the seg fault, even doing an SSL_free or SSL_shutdown on it causes a seg fault</p>
  
  <p>Compiler info:</p>
  
  <p>gcc main.c -lssl -lcrypto -o main</p>