C例子代码-3

// gcc -omain main.c -lssl -lcrypto
// export LD_LIBRARY_PATH=/usr/local/lib/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


const char * mail_server = "pop.qq.com"; 

int s;
SSL *ssl;


void init(){
    // domain name -> IP
    // struct addrinfo hints;
    // struct addrinfo *result = NULL;

    // hints.ai_flags = 0;
    // hints.ai_family = AF_INET;
    // hints.ai_socktype = SOCK_STREAM;
    // hints.ai_protocol = 0;

    // int r = getaddrinfo(mail_server, "pop3", &hints, &result); // return result in result pointer;
    // struct sockaddr_in *addr = (struct sockaddr_in*)(result->ai_addr->sa_data); 
    // printf("ip:%s\n", inet_ntoa(addr->sin_addr)); 
    // printf("port:%hd\n", addr->sin_port); 
    // Socket
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("14.18.175.202"); // 163.177.65.211// 163.177.65.209 175.202.0.0
    addr.sin_port = htons(995);

    s = socket(AF_INET, SOCK_STREAM, 0);

    int r = connect(s, (struct sockaddr*)&addr, sizeof(addr));
    // printf("%d\n", r);

    // SSL
    SSL_CTX *ctx;
    const SSL_METHOD *meth;
    X509 *server_cert;
    SSLeay_add_ssl_algorithms();
    meth = SSLv23_client_method();
    SSL_load_error_strings();
    ctx = SSL_CTX_new(meth);
    // SSL - Socket
    ssl = SSL_new(ctx);
    SSL_set_fd(ssl, s);
    SSL_connect(ssl);
    //  
    server_cert = SSL_get_peer_certificate(ssl);
    char *str = X509_NAME_oneline(X509_get_subject_name(server_cert), NULL, 0);
    // printf("%s\n", str);
    OPENSSL_free(str);

    str = X509_NAME_oneline(X509_get_issuer_name(server_cert), NULL, 0);
    // printf("%s\n", str);
    OPENSSL_free(str);
}

int send_data(SSL *sl, const char *mail_cmd){
    return SSL_write(sl, mail_cmd, strlen(mail_cmd));
}

int recv_data(SSL *sl, char *buf, size_t len){
    return SSL_read(sl, buf, len);
}

int  main(){
    // init
    init();

    // get server
    char data[1024 * 4]={0};
    recv_data(ssl, data, sizeof(data));
    printf("%s\n", data);

    // login - mail
    send_data(ssl, "user [email protected]\r\n");
    recv_data(ssl, data, sizeof(data));
    printf("%s\n", data);

    // login - password
    send_data(ssl, "pass olgmvqwywklncabg\r\n");
    recv_data(ssl, data, sizeof(data));
    printf("%s\n", data);

    // mamage mail
    send_data(ssl, "list\r\n");
    recv_data(ssl, data, sizeof(data));
    printf("%s\n", data);

    send_data(ssl, "retr 1\r\n");
    recv_data(ssl, data, sizeof(data));
    printf("%s\n", data);

    return 0;
    
    
/*

echo M9mpTqh4QKvq/CEuND6mU+F9caxx14tbL4CwzQFa1Z97Ghjj6sa4eHZc0lP+bEGqmZvuJjiTMjhcKonOQ6hgyVLFmtfZE7+Dco3pAk6XbHnJkhNuGz7qnwFpUB+9WQvHS43LmPh8+LL/YAIkLa09RhpIjBboL8D0Qg== | base64 -d
*/
}

你可能感兴趣的:(C例子代码-3)