Use getaddrinfo to recognize hostname

 

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
 
#ifndef   NI_MAXHOST
#define   NI_MAXHOST 1025
#endif

int main(int argc, const char *argv[]) 
{
    struct addrinfo * result;
    struct addrinfo * res;
    int error;

    if (argc != 2) {
      printf("usage: program hostname\n");
      return 1;
    }
 
    /* hint */
    struct addrinfo hint;
    hint.ai_family = AF_INET;
    hint.ai_flags = 0;
    hint.ai_protocol = 0;
    /* if set to 0, 3 addrinfos will be returned */
    hint.ai_socktype = SOCK_STREAM;

    /* must be set to 0 or NULL */
    hint.ai_addrlen = 0;
    hint.ai_addr = NULL;
    hint.ai_canonname = NULL;
    hint.ai_next = NULL;

    error = getaddrinfo(argv[1], NULL, &hint, &result);
 
    if (error != 0) {   
        fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
        return 1;
    }   
 
    /* loop over all returned results and do inverse lookup */
    for (res = result; res != NULL; res = res->ai_next) {   
        char hostname[NI_MAXHOST] = "";

        error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0); 
 
        if (error != 0) {
            fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error));
            continue;
        }
 
        if (*hostname) {
            printf("hostname: %s\n", hostname);
        }
 
    }   
 
    freeaddrinfo(result);
 
    return 0;
}
 

你可能感兴趣的:(socket)