gethostbyname()

本文详细解析了gethostbyname函数的使用方法及其返回的主机信息结构,包括主机名、别名和IP地址的获取过程。通过示例代码展示了如何调用gethostbyname函数,并解释了如何解析返回的主机信息结构来获取主机的相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>


/*原型:
 struct hostent *gethostbyname(const char *name); //调用失败,返回 NULL
 */
/*结构:
struct hostent {
 char *h_name;      //主机的规范名
 char **h_aliases;  //主机的别名,有的主机有多个,为了记忆
 int h_addrtype;    //主机的IP类型,AF_INET/AF_INET6
 int h_length;      //主机IP的长度
 char **h_addr_list;//主机的IP地址,可能有多个。注意:网络字节序,打印IP,需要调用inet_ntop()
 };*/

     
int main(int argc, char *argv[]){     
    char ipstring[20],**alias,**iplist;
    struct hostent* host;
    if( (host=gethostbyname(argv[1])) == NULL ){
        printf("gethostbyname error for host\n");
        exit(-1);
    }
    /*打印主机的规范名*/
    printf("official hostname:%s\n", host->h_name);
    /*主机可能有多个别名*/
    for( alias=host->h_aliases; *alias!=NULL;alias++ ){
        printf("alias:%s\n", *alias);
    }
    /*根据地址类型,将地址打印出来*/
    switch(host->h_addrtype){
        case AF_INET:
        case AF_INET6:
            for(iplist = host->h_addr_list;*iplist!=NULL;iplist++){
                //const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
                //返回值 和dst 相同

                inet_ntop(host->h_addrtype, *host->h_addr_list, ipstring, sizeof(ipstring));
                printf("address:%s\n", ipstring);
            }
        break;
        default:
            printf("unknow address\n");
    }
    return 0;
    
}


结果(多次运行,结果不同,但IP 都是正确的,只是不能同时显示出来(Why?)):

$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.92
address:111.13.100.92

$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.91
address:111.13.100.91

$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.92
address:111.13.100.92




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值