Search code examples
c++socketssmtp

Connecting to SMTP server with C++ on Windows


I'm trying to create a client manager. I have read some information about sockets. I'm doing my first steps and I've got my first problem.

This is my code:

 #include <iostream>
 #include <cstdio>
 #include <winsock2.h>
 #include <windows.h>
 #pragma comment (lib, "ws2_32.lib")

 using namespace std;
 const int VERSION_MAJOR = 1;
 const int VERSION_MINOR = 1;

 int main()
 {
    WSADATA WSData;
    SOCKET sock;
    struct sockaddr_in addr;

    WSAStartup(MAKEWORD(VERSION_MAJOR, VERSION_MINOR), &WSData)

    sock = socket(AF_INET, SOCK_STREAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(25); // или любой другой порт...
    hostent *server_adress = gethostbyname("smtp.gmail.com");
    addr.sin_addr.s_addr = *((unsigned long *)server_adress->h_addr_list[0]);   
    int con = connect(sock, (struct sockaddr *) &addr, sizeof(addr));
    cout << "connect status " << con << '\n';

   return 0;
}

connect() returns -1

Where is the mistake?


Solution

  • In the following line:

    sock = socket(AF_INET, SOCK_STREAM, 0);
    

    You do not specify a protocol. You should change it to

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    

    This is the kind of protocol you are going to want to establish with something such as a mailing service.