DnsResolver sample

This commit is contained in:
2024-04-29 13:16:14 -04:00
parent cec6132acc
commit 7f4578f122
2 changed files with 14 additions and 43 deletions

View File

@@ -12,7 +12,7 @@ namespace Sockets
{
/// Internet Protocol Version
/// @see https://www.geeksforgeeks.org/differences-between-ipv4-and-ipv6/
enum class InternetProtocol
enum class InternetProtocol : uint8_t
{
IPv4, IPv6
};

View File

@@ -76,60 +76,31 @@ int main(int argc, char *argv[])
/// DNS Resolver sample program from ChatGPT
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <cstring>
#include "Sockets/DNSResolver.hpp"
int main(int argc, char *argv[])
{
if (argc != 2)
{
std::cerr << "Usage: " << argv[0] << " <hostname>" << std::endl;
return 1;
//std::cerr << "Usage: " << argv[0] << " <hostname>" << std::endl;
//return 1;
}
const char* hostname = argv[1];
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
const char* hostname = "git.redacted.cc";//argv[1];
auto result = Sockets::ResolveDNS(hostname);
std::memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(hostname, NULL, &hints, &res)) != 0)
if (result.Success)
{
std::cerr << "getaddrinfo: " << gai_strerror(status) << std::endl;
return 2;
}
std::cout << "IP addreses for " << hostname << ":" << std::endl;
for (p = res; p != NULL; p = p->ai_next)
{
void* addr;
std::string ipver;
if (p->ai_family == AF_INET) // IPv4
for (auto hostname : result.ResolvedHostnames)
{
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
if (hostname.ProtocolVersion == Sockets::InternetProtocol::IPv4) {
std::cout << "IPv4: " << hostname.Host << std::endl;
} else if (hostname.ProtocolVersion == Sockets::InternetProtocol::IPv6) {
std::cout << "IPv6: " << hostname.Host << std::endl;
}
}
// Convert the IP to a string and print it
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
std::cout << " " << ipver << ": " << ipstr << std::endl;
}
freeaddrinfo(res); // free the linked list
return 0;
}
// Compile this code and run it with a hostname as an argument, like so:
// ./dns_resolver www.google.com
// This program will resolve the IP addresses associated with the given hostname and print them to the console.