Skip to content

Commit

Permalink
Added DNS resolution for host addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
ksmit799 committed Aug 24, 2023
1 parent 58a99a6 commit 12cc568
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/messagedirector/message_director.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#ifdef ARDOS_WANT_DB_SERVER
#include "../database/database.h"
#endif
#include "../net/address_utils.h"
#include "../stateserver/state_server.h"
#include "../util/config.h"
#include "../util/globals.h"
Expand Down Expand Up @@ -96,7 +97,8 @@ MessageDirector::MessageDirector() {

// Start connecting/listening!
_listenHandle->bind(_host, _port);
_connectHandle->connect(rHost, rPort);
_connectHandle->connect(AddressUtils::resolve_host(g_loop, rHost, rPort),
rPort);
}

/**
Expand Down
51 changes: 51 additions & 0 deletions src/net/address_utils.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include "address_utils.h"

#include "../util/logger.h"

namespace Ardos {

std::string AddressUtils::resolve_host(const std::shared_ptr<uvw::loop> &loop,
const std::string &host,
unsigned int port) {
// First, test if we have a valid IPv4 address.
sockaddr_in sockaddr;
if (uv_ip4_addr(host.c_str(), port, &sockaddr) == 0) {
return host;
}

// Next, test if we have a valid IPv6 address.
sockaddr_in6 sockaddr6;
if (uv_ip6_addr(host.c_str(), port, &sockaddr6) == 0) {
return host;
}

// We don't, lets try to resolve an IP via DNS.
auto dnsRequest = loop->resource<uvw::get_addr_info_req>();
auto dnsResult = dnsRequest->addr_info_sync(host, std::to_string(port));
if (!dnsResult.first) {
Logger::Error(
std::format("[NET] Failed to resolve host address: {}:{}", host, port));
exit(1);
}

char addr[INET6_ADDRSTRLEN];
if (inet_ntop(dnsResult.second->ai_family,
get_in_addr(dnsResult.second->ai_addr), addr,
dnsResult.second->ai_addrlen)) {
return std::string(addr);
}

Logger::Error(
std::format("[NET] Failed to parse host address: {}:{}", host, port));
exit(1);
}

void *AddressUtils::get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in *)sa)->sin_addr);
}

return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}

} // namespace Ardos
23 changes: 23 additions & 0 deletions src/net/address_utils.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#ifndef ARDOS_ADDRESS_UTILS_H
#define ARDOS_ADDRESS_UTILS_H

#include <memory>
#include <string>

#include <uvw.hpp>

namespace Ardos {

class AddressUtils {
public:
static std::string resolve_host(const std::shared_ptr<uvw::loop> &loop,
const std::string &host,
unsigned int port = 0);

private:
static void *get_in_addr(struct sockaddr *sa);
};

} // namespace Ardos

#endif // ARDOS_ADDRESS_UTILS_H

0 comments on commit 12cc568

Please sign in to comment.