core-legacy/helpers/open_tcp_connection.cc

35 lines
852 B
C++

#include <helpers.h>
#include <netdb.h>
#include <errno.h>
#include <string.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 " << strerror(errno);
freeaddrinfo(res);
return 0;
}
freeaddrinfo(res);
return s;
}