Thread: getnameinfo()

  1. #1
    Registered User
    Join Date
    Jan 2006
    Location
    Europe/Belgrade
    Posts
    78

    getnameinfo()

    Hi,
    as I understand, getnameinfo() is used for reverse lookup i.e. to get hostname from the IP address. So, what's wrong with the following code
    Code:
    #include <arpa/inet.h>
    #include <netdb.h>
    
    int main()
    {
      struct sockaddr_in sa;
      inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr);
    
      char node[NI_MAXHOST];
      int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
      if (res)
     {
        printf("error: %d\n", res);
        printf("%s\n", gai_strerror(res));
      }
    
      return 0;
    }
    it exits with the error ai_family not supported?

    If I use getnameinfo() with the address obtained with getaddrinfo() for example with
    Code:
    int main()
    {
      struct addrinfo* ailist;
      struct addrinfo* aip;
      struct addrinfo hint;
      struct sockaddr_in* sinp;
      const char* addr;
      char abuf[INET_ADDRSTRLEN];
    	
      hint.ai_flags = AI_CANONNAME;
      hint.ai_family = 0;
      hint.ai_socktype = 0;
      hint.ai_protocol = 0;
      hint.ai_addrlen = 0;
      hint.ai_canonname = NULL;
      hint.ai_addr = NULL;
      hint.ai_next = NULL;
      const char* host = "localhost";
      const char* serv = "ftp";
    
      if (getaddrinfo(host, NULL, &hint, &ailist))
      {
        printf("error: getaddrinfo()\n");
        exit(1);
      }
    
      for (aip = ailist; aip != NULL; aip = aip->ai_next)
      {
        char buf[512];
        if (getnameinfo(aip->ai_addr, sizeof(struct sockaddr), buf, 512, NULL, 0, 0) == 0)
          printf("%s\n", buf);
      }
    }
    then resolving works fine.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Are you sure you've correctly initialized the sockaddr_in struct? You should probably set the sin_family field to AF_INET.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Jan 2006
    Location
    Europe/Belgrade
    Posts
    78
    Thanks, that was the problem. Here's the code which works:
    Code:
    #include <arpa/inet.h>
    #include <netdb.h>
    
    int main()
    {
      struct sockaddr_in sa;
      sa.sin_family = AF_INET;
      inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr);
    
      char node[NI_MAXHOST];
      int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
      if (res)
      {
        printf("&#37;s\n", gai_strerror(res));
        exit(1);
      }
      printf("%s\n", node);
    
      return 0;
    }
    Last edited by karas; 10-04-2007 at 01:00 AM.

Popular pages Recent additions subscribe to a feed