EHS/src/io/socket/DNS.cpp

73 lines
1.7 KiB
C++

#include "ehs/io/socket/DNS.h"
#include "ehs/Log.h"
#if defined(EHS_OS_WINDOWS)
#include <WinSock2.h>
#include <WS2tcpip.h>
#elif defined(EHS_OS_LINUX)
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
namespace ehs
{
Str_8 DNS::Resolve(const Str_8& hostname)
{
#if defined(EHS_OS_WINDOWS)
WSADATA data = {};
Int_32 wsaCode = WSAStartup(MAKEWORD(2, 2), &data);
if (wsaCode)
{
EHS_LOG_INT("Error", 0, "Failed to start WSA with error #" + Str_8::FromNum(wsaCode) + ".");
return {};
}
#endif
addrinfo* result = nullptr;
Int_32 code = getaddrinfo(hostname, nullptr, nullptr, &result);
if (code)
{
EHS_LOG_INT("Error", 1, "Failed to resolve host with error #" + Str_8::FromNum(code) + ".");
return {};
}
#if defined(EHS_OS_WINDOWS)
if (WSACleanup() == SOCKET_ERROR)
{
EHS_LOG_INT("Error", 2, "Failed to shutdown WSA with error #" + Str_8::FromNum(WSAGetLastError()) + ".");
return {};
}
#endif
if (result->ai_family == AF_INET6)
{
Str_8 ipResult(INET6_ADDRSTRLEN);
inet_ntop(result->ai_family, &((sockaddr_in6*)result->ai_addr)->sin6_addr, ipResult, INET6_ADDRSTRLEN);
ipResult.ExactSize();
freeaddrinfo(result);
return ipResult;
}
else if (result->ai_family == AF_INET)
{
Str_8 ipResult(INET_ADDRSTRLEN);
inet_ntop(result->ai_family, &((sockaddr_in*)result->ai_addr)->sin_addr, ipResult, INET_ADDRSTRLEN);
ipResult.ExactSize();
freeaddrinfo(result);
return ipResult;
}
return {};
}
}