controller-legacy/helpers/open_discovery_socket.c

58 lines
1.4 KiB
C
Raw Normal View History

2020-04-13 22:50:55 +00:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <logger.h>
#include <helpers.h>
int
helper_open_discovery_socket(uint16_t discovery_port)
{
struct addrinfo hints, *res;
int fd, status;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // use ipv4
hints.ai_socktype = SOCK_DGRAM; //set socket flag
hints.ai_flags = AI_PASSIVE; // get my IP
char discovery_port_str[6];
sprintf(discovery_port_str, "%u", discovery_port);
//get connection info for our computer
if ((status = getaddrinfo(NULL, discovery_port_str, &hints, &res)) != 0)
{
2020-04-24 13:08:26 +00:00
LOG_FATAL("getaddrinfo: %s\n", gai_strerror(status));
2020-04-13 22:50:55 +00:00
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
//creating socket
fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
int yes = 1;
// lose the pesky "Address already in use" error message
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
{
2020-04-24 13:08:26 +00:00
LOG_FATAL("setsockopt: %s\n", strerror(errno));
2020-04-13 22:50:55 +00:00
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
if (bind(fd, res->ai_addr, res->ai_addrlen) == -1)
{
2020-04-24 13:08:26 +00:00
LOG_FATAL("bind: %s\n", strerror(errno));
2020-04-13 22:50:55 +00:00
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
freeaddrinfo(res);
2020-04-24 13:08:26 +00:00
LOG_INFO("opened discovery socket on port %u\n", discovery_port);
2020-04-13 22:50:55 +00:00
return fd;
}