-
-
Save primeos/8f7f8e1e95518076ef38924125a2f921 to your computer and use it in GitHub Desktop.
Quick hack for https://github.com/NixOS/nixpkgs/pull/76542
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdbool.h> | |
#include <netdb.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
// gcc -Wall hostname-test.c -o hostname-test | |
// Example for /etc/hosts: | |
// 127.0.0.1 localhost | |
// ::1 localhost | |
// 127.0.0.1 nixos-unstable.test.tld nixos-unstable | |
// ::1 nixos-unstable.test.tld nixos-unstable | |
enum allowedAfs {IPv4, IPv6}; | |
void showhostnameaf(const char* hostname, enum allowedAfs af) { | |
char *afname; | |
struct hostent *he; | |
if (af == IPv4) { | |
he = gethostbyname(hostname); | |
afname = "IPv4"; | |
} else if (af == IPv6) { | |
he = gethostbyname2(hostname, PF_INET6); | |
afname = "IPv6"; | |
} else { | |
return; | |
} | |
printf("Hostname (%s): %s\n", afname, hostname); | |
printf("- Canonical name: %s\n", he->h_name); | |
printf("- Aliases:"); | |
for (char **h_aliases = he->h_aliases; *h_aliases != NULL; h_aliases++) { | |
printf(" %s", *h_aliases); | |
} | |
printf("\n"); | |
} | |
void showhostname(const char* hostname) { | |
showhostnameaf(hostname, IPv4); | |
showhostnameaf(hostname, IPv6); | |
} | |
void showhostnameaddr(const char* host, int type) { | |
struct hostent *he; | |
if (type == AF_INET) { | |
struct in_addr addr; | |
inet_pton(type, host, &addr); | |
he = gethostbyaddr(&addr, sizeof(addr), type); | |
} else if (type == AF_INET6) { | |
struct in6_addr addr; | |
inet_pton(type, host, &addr); | |
he = gethostbyaddr(&addr, sizeof(addr), type); | |
} else { | |
return; | |
} | |
printf("Address: %s\n", host); | |
printf("- Canonical name: %s\n", he->h_name); | |
printf("- Aliases:"); | |
for (char **h_aliases = he->h_aliases; *h_aliases != NULL; h_aliases++) { | |
printf(" %s", *h_aliases); | |
} | |
printf("\n"); | |
} | |
int main() { | |
char hostname[256]; | |
gethostname(hostname, sizeof(hostname)/sizeof(hostname[0])); | |
showhostname(hostname); | |
showhostnameaddr("127.0.0.1", AF_INET); | |
showhostnameaddr("::1", AF_INET6); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment