Jmmc
Jmmc

Reputation: 13

Failed to connect to a SMTP server

I created a simple code to connect to a Gmail SMTP server, but the function connect() returns -1 (SOCKET_ERROR). What's wrong with this code?

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>

int main()
{
    WSADATA wsaData;
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("smtp.gmail.com");
    addr.sin_port = htons(587);

    //WSA STARTUP
    if (WSAStartup(MAKEWORD(2, 2), &wsaData))
    {
        std::cout << "Failed to startup wsa.\n";
        return 1;
    }

    // GNIAZDO DLA KLIENTA
    SOCKET mSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (mSocket == INVALID_SOCKET)
    {
        std::cout << "Socket error: " << WSAGetLastError();
        WSACleanup();
        return 1;
    }
    //LACZENIE Z SERWEREM
    int status = connect(mSocket, (SOCKADDR*)&addr, sizeof(addr));
    std::cout << "Connection status: " << status;

    return 0;
}

Upvotes: 1

Views: 126

Answers (2)

Michael Chourdakis
Michael Chourdakis

Reputation: 11178

The answer below is correct, but since you are using Windows, an easier option is WSAConnectByName which avoids all the old-fashioned htons/getaddrinfo stuff and also works with IPv6 automatically.

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52591

inet_addr expects an IP address in dot notation, as in "1.2.3.4". It does not resolve domain names. You are looking for getaddrinfo

Upvotes: 5

Related Questions