netex/src/net/netex.c

86 lines
2.5 KiB
C

#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include "netex.h"
#include "config.h"
#define PORT_NUM_LENGHT 6
void netex_init(void)
{
// OpenSSL
PRINT_LINE("Initializing OpenSSL...");
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
void netex_shutdown(void)
{
// OpenSSL
ERR_free_strings();
EVP_cleanup();
}
int setup_socket(const int port, const char* hostname)
{
struct addrinfo *cur_addrdinfo;
struct addrinfo hints_addrinfo = {0};
int sock_fd = 0;
hints_addrinfo.ai_family = AF_UNSPEC;
hints_addrinfo.ai_socktype = SOCK_DGRAM;
hints_addrinfo.ai_flags = AI_PASSIVE;
hints_addrinfo.ai_protocol = 0;
hints_addrinfo.ai_canonname = NULL;
hints_addrinfo.ai_addr = NULL;
hints_addrinfo.ai_next = NULL;
char port_str[PORT_NUM_LENGHT];
const int print_result = snprintf(port_str, PORT_NUM_LENGHT, "%d", port);
if (print_result < 0)
{
ERROR("Failed to convert port to string!");
return -1;
}
if (print_result >= PORT_NUM_LENGHT)
WARN("Convert output string truncated (port) to value: '%s'", port_str);
if (getaddrinfo(hostname, port_str, &hints_addrinfo, &cur_addrdinfo) != 0)
{
ERROR("Could not get the address info of hostname: '%s'", hostname);
return -1;
}
//TODO: Need fihure out why data from getaddrinfo is not working.
/*for (const struct addrinfo* tmp_addrinfo = cur_addrdinfo; tmp_addrinfo != NULL; tmp_addrinfo = tmp_addrinfo->ai_next)
{
sock_fd = socket(tmp_addrinfo->ai_family, tmp_addrinfo->ai_socktype, tmp_addrinfo->ai_protocol);
if (sock_fd == -1)
continue;
if (bind(sock_fd, tmp_addrinfo->ai_addr, tmp_addrinfo->ai_addrlen) == 0)
break; // Succesfull bind to the hostname
close(sock_fd); // Close the socket en if there are more 'addrinfo' retry in the while loop.
}*/
freeaddrinfo(cur_addrdinfo);
struct sockaddr_in sockaddr;
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0)
{
ERROR("Failed to created socket");
return -1;
}
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(6920);
sockaddr.sin_addr.s_addr = INADDR_ANY;
const int bind_result = bind(sock_fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
if (bind_result != 0)
{
ERROR("Could not bind!");
close(sock_fd);
return -1;
}
return sock_fd;
}