#include #include #include #include #include #include #include #include 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) { LOG_FATAL("getaddrinfo: %s\n", gai_strerror(status)); 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) { LOG_FATAL("setsockopt: %s\n", strerror(errno)); freeaddrinfo(res); exit(EXIT_FAILURE); } if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) { LOG_FATAL("bind: %s\n", strerror(errno)); freeaddrinfo(res); exit(EXIT_FAILURE); } freeaddrinfo(res); LOG_INFO("opened discovery socket on port %u\n", discovery_port); return fd; }