Reputation:
I know this question was asked here before and I read all the answers, but wasn't able to resolve this on my own. Here's the deal: I have to make a program which takes a bunch of internet addresses (like google.com, www.root.cz) and prints out an official name, alternative names and IP adresses and domain names of aliases. We've got a sample code for 1 address without the aliases domain name, so I used it, then made a few changes to fit my needs. The code looks like this:
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main (int argc, char *argv[])
{
for (int i = 1; i < argc; ++i){
hostent *H = gethostbyname(argv[i]);
if (H == NULL)
{
std::cerr << "Nepodařilo se zjistit adresu" << std::endl;
return -1;
}
std::cout << "Oficiální jméno: " << H->h_name << std::endl;
std::cout << "Alternativy: " << std::endl;
/* Budeme procházet pole H->h_aliases. Pole je ukončené NULL.*/
char **alternativy = H->h_aliases;
while(*alternativy != NULL)
{
std::cout << "\t" << *(alternativy++) << std::endl;
}
/* Budeme procházet pole H->h_addr_list. Pole je ukončené NULL.
Zvolíme jiný postup než v předchozím případě.*/
std::cout << "Adresy: " << std::endl;
for(int i = 0; H->h_addr_list[i] != NULL; ++i)
{
/* H->h_addr_list je binární forma IP adresy. Pro převod na
tečkovou konvenci použijeme inet_ntoa.*/
const char* addr = inet_ntoa(*(in_addr *)H->h_addr_list[i]);
hostent *name = gethostbyaddr(addr, sizeof(addr), AF_INET);
std::cout<<addr<<"->"<<name<<std::endl;
}
std::cout<<std::endl;
}
return 0;
}
Everything works fine. Only name is always null. I tried running this on ubuntu 12.04 I have on my laptop and on virtual Debian Squeeze(don't remember number). I checked some of the config files as stated in previous questions. Also tried configuring more DNS servers. Nothing works. I also tried using getnameinfo, but for some reason it always returned only given IP address. Any help will be greatly appreciated.
Upvotes: 0
Views: 1194
Reputation: 465
You are passing wrong format of IP that you want to translate back to hostname.
Change your for like this.
for(int i = 0; H->h_addr_list[i] != NULL; ++i)
{
/* H->h_addr_list je binární forma IP adresy. Pro převod na tečkovou konvenci použijeme inet_ntoa.*/
const char* addr = inet_ntoa(*(in_addr *)H->h_addr_list[i]);
hostent *name = gethostbyaddr((in_addr *)H->h_addr_list[i], sizeof(in_addr), AF_INET);
std::cout<<addr<<"->"<<name->h_name<<std::endl;
}
also look for getaddrinfo()
because gethotbyname(),gethostbyaddr()
are obsolete functions
Upvotes: 1
Reputation: 326
There is an error calling gethostbyaddr() with incorrect parameters (it expects a binary address, not a string), and another error displaying the returned name (which is a field of hostent). I have tried the following and seems to work fine:
hostent *name = gethostbyaddr(H->h_addr_list[i], sizeof (struct in_addr), AF_INET);
std::cout << addr << "->" << name->h_name << std::endl;
Upvotes: 0