4
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>

int main(void)
{
    int ret;
    struct addrinfo hints;
    struct addrinfo *res;
    struct addrinfo *p;

    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;            // IPV4 or IPV6
    hints.ai_socktype = SOCK_STREAM;        // TCP
    hints.ai_flags = AI_CANONNAME;

    if ((ret=getaddrinfo("216.58.221.36", NULL, &hints, &res)) != 0) {     // here 
        exit(-1);
    }
    p = res; 
    printf("%s\n", p->ai_canonname);
    return 0;
}

If the first argument of getaddrinfo is 216.58.221.36 as above, then the output is: 216.58.221.36.

If the first argument of getaddrinfo is www.google.com, then the output is www.google.com.

Why? Shouldn't ai_canonname have the same value in both cases?

roschach
  • 8,390
  • 14
  • 74
  • 124
hel
  • 581
  • 10
  • 26
  • 1
    Why would you expect that? It returns the canonical form of whatever input you gave to `getaddrinfo()`, whether that is an IP string or a hostname. Did you read the [`getaddrinfo()` documentation](http://man7.org/linux/man-pages/man3/getaddrinfo.3.html)? "*If hints.ai_flags includes the AI_CANONNAME flag, then the ai_canonname field of the first of the addrinfo structures in the returned list is set to point to the official name of the host.*" – Remy Lebeau Jan 18 '16 at 06:04
  • Yes,I have read it.I thought that official name may be unique. Maybe it's a Fully Qualified Domain Name like "www. ....". So when the output is IP Adrdress , I'm confused. Are FQDN and canonical name the same thing?Thanks! – hel Jan 18 '16 at 07:51
  • If you pass an IP address to `getaddrinfo()`, it is not going to perform a lookup trying to find the hostname, as you have seen. It should just return the canonical format of the IP. Try passing it a short IPv6 address and it should expand. See [this example](http://stackoverflow.com/questions/18884251/getaddrinfo-i-am-not-getting-any-canonname) of a case where passing in a real hostname will return a different canonical hostname. – Remy Lebeau Jan 18 '16 at 21:58
  • Really clear and thanks for your time! – hel Jan 19 '16 at 01:42

0 Answers0