如何在c中发出https请求?

时间:2016-10-28 10:39:25

标签: c https openssl

我一直在尝试使用openssl在c中发出https请求。但是由于某些原因,openssl给了我一个分段错误。我不确定究竟发生了什么,但SSL_read和SSL_free给我一个分段错误。

我已经设置了一个类似于类的结构,它包含有关连接的所有信息。

https.h

public func setMaskTo(setMask:UIView, corner:UIRectCorner) -> Void {
        let round = UIBezierPath(roundedRect: setMask.bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: 10, height: 10))
        let shape = CAShapeLayer()
        shape.frame = round.bounds
        shape.path = round.cgPath
        setMask.layer.mask = shape
    }

setMaskTo(setMask: self, corner: [.topLeft, .topRight])

我这样调用上面的代码

的main.c

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 *)&server , sizeof(server)) < 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) <0) {
        return 0;
    }
    return 1;
}

void close_sock(struct sock s) {
    SSL_shutdown(s.conn);
    close(s.socket);
}

所以输出就像这样

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);
    }
}

虽然上面给出的main.c尝试在产生seg错误时读取,但即使对其执行SSL_free或SSL_shutdown也会导致seg错误

编译器信息:

gcc main.c -lssl -lcrypto -o main

0 个答案:

没有答案