#include <helpers.h>
#include <netdb.h>
#include <trantor/utils/Logger.h>

int
helpers::open_tcp_connection(char *host, char *port)
{
    int s, status;
    struct addrinfo hints{}, *res;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    if ((status = getaddrinfo(host, port, &hints, &res)) != 0)
    {
        LOG_ERROR << "Error getting address info: " << gai_strerror(status);
        freeaddrinfo(res);
        return 0;
    }

    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); //creating Socket

    if ((status = connect(s, res->ai_addr, res->ai_addrlen)) != 0)
    {
        LOG_ERROR << "Error opening connection " << status;
        freeaddrinfo(res);
        return 0;
    }

    freeaddrinfo(res);

    return s;
}