core-legacy/helpers/bind_tcp_server.cc

44 lines
1,016 B
C++
Raw Normal View History

2019-07-14 22:39:37 +00:00
#include <netdb.h>
#include <trantor/utils/Logger.h>
#include <helpers.h>
#include "config.h"
int
helpers::bind_tcp_server(const char *addr, const char *port, int max_client_backlog)
{
2019-07-20 12:51:45 +00:00
struct addrinfo hints{}, *res;
2019-07-14 22:39:37 +00:00
int fd;
int status;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((status = getaddrinfo(addr, port, &hints, &res)) != 0)
{
LOG_ERROR << "Error getting address info: " << gai_strerror(status);
}
fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if ((status = bind(fd, res->ai_addr, res->ai_addrlen)) == -1)
{
LOG_ERROR << "Error binding socket. " << status;
freeaddrinfo(res);
return -1;
}
if ((status = listen(fd, max_client_backlog)) == -1)
{
LOG_ERROR << "Error setting up listener. " << status;
freeaddrinfo(res);
return -1;
}
freeaddrinfo(res);
return fd;
}