Resolving names and IPs
Here is two examples of name resolving in linux.. I use getaddrinfo() and getnameinfo() respectively..getaddrinfo: given a name retuns all translated IPs, one per line
/*
* File: getaddrinfo.c
* Compile: gcc getaddrinfo.c -o getaddrinfo
* Usage: ./getaddrinfo FQN
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
int error;
struct addrinfo saddr, *psaddr, *ptr;
memset(&saddr, '\0', sizeof(saddr));
saddr.ai_family = AF_INET;
saddr.ai_socktype = SOCK_STREAM;
error = getaddrinfo(argv[1], NULL, &saddr, &psaddr);
if (error) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
exit(EXIT_FAILURE);
}
for (ptr = psaddr; ptr; ptr = ptr->ai_next) {
puts(inet_ntoa(((struct sockaddr_in *)
ptr->ai_addr)->sin_addr));
}
return 0;
}
getnameinfo: Given an IP returns the name that first resolves to it.
/*
* File: getnameinfo.c
* Compile: gcc getnameinfo.c -o getnameinfo
* Usage: ./getnameinfo IP
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static char hostname[255];
int main(int argc, char **argv)
{
int error;
struct sockaddr_in saddr_in;
memset(&saddr_in, '\0', sizeof(saddr_in));
saddr_in.sin_family = AF_INET;
error = inet_aton(argv[1], &saddr_in.sin_addr);
if (error == 0) {
perror("inet_aton");
exit(EXIT_FAILURE);
}
error = getnameinfo((struct sockaddr *)&saddr_in, sizeof(saddr_in),
hostname, sizeof(hostname),
NULL, 0, NI_NAMEREQD);
if (error) {
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(error));
exit(EXIT_FAILURE);
}
puts(hostname);
return 0;
}
Cheers