core-legacy/helpers/open_tcp_connection.cc

33 lines
791 B
C++
Raw Normal View History

2019-07-29 20:02:38 +00:00
#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 addressinfo: " << 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";
freeaddrinfo(res);
return 0;
}
freeaddrinfo(res);
return s;
}