gethostbyname & gethostbyaddr使用方法

zxh821112發表於2015-06-01

#include <stdio.h>

#include <netdb.h>

#include <unistd.h>

#include <arpa/inet.h>


int main(int argc, char* argv[]){

    char hostName[1024];

    struct hostent * localHost;

     struct hostent * localHost1;

    char ip_str[INET_ADDRSTRLEN];

    const char* p = NULL;

    int i, j;

    struct in_addr ip;

    localHost = gethostbyname(argv[1]);

    gethostname(hostName, sizeof(hostName));

    printf("localHost->h_name = %s h_addr= %s argc=%d hostName=%s\n", localHost->h_name, localHost->h_addr, argc,hostName);

    //p = inet_ntop(AF_INET, (struct in_addr*)localHost->h_addr, ip_str, INET_ADDRSTRLEN);

    //p = inet_ntop(AF_INET, localHost->h_addr, ip_str, INET_ADDRSTRLEN);

    //if (p != NULL) {

    //    printf("--ip_str = %s\n", ip_str);

    //}

    

    for(i = 0; localHost->h_addr_list[i] != 0; i++) {

        p = inet_ntop(AF_INET, localHost->h_addr_list[i], ip_str, INET_ADDRSTRLEN);

        if (p != NULL) {

            printf("ip_str = %s\n", ip_str);

        }else{

            printf("ip_str is null!\n");

        }

    }

    

     printf("addr is = %s\n", argv[2]);

    j = inet_pton(AF_INET, argv[2], &ip);

    if (j == 1) {

        printf("ok!\n");

        localHost1 = gethostbyaddr((const char*)&ip, sizeof(ip), AF_INET);

        if (localHost1 != NULL) {

             printf("localHost1->h_name = %s\n", localHost1->h_name);

        }

       

    }

    

return 0;

}

相關文章