1

I'm trying to connect to smtp.gmail.com with C++ code, and I think I need openSSL. I installed it and successfully connect to server with command line,

openssl s_client -starttls smtp -connect smtp.gmail.com:587

but I got trouble when establish connection in code, see the last few sentences of the code.

Could anyone please help?

    void main ()
    {
        int err;
        int sd;
        struct sockaddr_in sa;
        SSL_CTX* ctx;
        SSL* ssl;
        X509* server_cert;
        char* str;
        const SSL_METHOD *meth;

        WSADATA wsaData;

        if(WSAStartup(MAKEWORD(2,2),&wsaData) != 0){
        printf("WSAStartup()fail:%d\n",GetLastError());
        return -1;
        } 

        SSL_library_init();

        SSL_load_error_strings(); 

        meth = TLSv1_2_client_method();
        ctx = SSL_CTX_new (meth); 
        CHK_NULL(ctx);


        // begin win socket .............................. 
        printf("Begin tcp socket...\n");

        sd = socket (AF_INET, SOCK_STREAM, 0); CHK_ERR(sd, "socket");

        memset (&sa, 0, sizeof(sa));
        sa.sin_family = AF_INET;
        sa.sin_addr.s_addr = inet_addr (SERVER_ADDR); /* Server IP */
        sa.sin_port = htons (PORT); /* Server Port number */

        err = connect(sd, (struct sockaddr*) &sa,  sizeof(sa)); 
        if( sd == SOCKET_ERROR  ) {
        std::cout<<"connect error."<<std::endl;
        return -1;
        }


        /* SSl negotiation .................. */
        printf("Begin SSL negotiation \n");

        ssl = SSL_new (ctx); 
        CHK_NULL(ssl);

        SSL_set_fd (ssl, sd);

    //ssl connect error here????        
    //What's wrong

        err = SSL_connect (ssl);
        if (err == -1)
        {
        ERR_print_errors_fp(stderr);
        }
    }
jww
  • 97,681
  • 90
  • 411
  • 885
Ronny
  • 11
  • 1
  • 1
    The protocol starts in plain text and then switches to TLS with the `STARTTLS` command. The bad guy can always force a downgrade by swallowing `STARTTLS` :) The server advertises TLS support by listing it in the extended hello (which the attacker can strip), and the client accepts it by reacting to the server advertisement (which the attacker previously stripped). Also see [What is the difference between ports 465 and 587?](http://stackoverflow.com/q/15796530) – jww Jun 17 '15 at 14:46
  • 1
    Can you show what error you're receiving? – ice13berg Jun 19 '15 at 07:44

0 Answers0