利用gethostbyname()和gethostbyaddr()函数获取主机完整信息

函数原型:

  • gethostbyname函数是通过主机名称获取主机的完整信息。name参数是目标主机的主机 名称。
  • gethostbyaddr函数是通过IP地址获取主机的完整信息。addr是网络字节序的IP地址,len参数是IP地址的长度,type参数是IP地址的类型(合法类型包括AF_INET,AF_INET6)
  • 两个函数的返回都是hostent结构体类型指针。hostent结构体定义如下:

 

代码实现:

  1. gethostbyname()
#include<stdio.h>
#include<netdb.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<arpa/inet.h>
int main(int argc, char * argv[])
{
    char **p1;
    char **p2;
    struct hostent *host;
    char hostname[60];
    int ret = 0;
    int i=0;
    char str[30];
    ret = gethostname(hostname,sizeof(hostname));
    printf("the hostname:%s\n",hostname);
    hostname[strlen(hostname)+1] = '\0';
    /*利用主机名称获取完整的主机信息*/
    host = gethostbyname(hostname);
    printf("the hostname after getosbyname: %s \n",host->h_name);
    /*主机别名列表*/
    printf("the other name of host:\n");
    for(p1=host->h_aliases; *p1!=NULL; p1++)
    {
        i++;
        printf("NO.%d:%s\n",i,p1[0]);
    }
    if(i==0)
    {
        printf("none\n");
    }
    i = 0;
    printf("the type of address:%d\n",host->h_addrtype);
    printf("the length of the address:%d\n",host->h_length);
    /*按照网络字节序列出的主机ip地址表*/
    printf("the IP of host:\n");
    switch(host->h_addrtype)
    {
        case AF_INET://ipv4
        case AF_INET6:
        {
            p2 = host->h_addr_list;
            while(*p2!=NULL)
            {
                printf("address:%s\n",inet_ntop(host->h_addrtype, *p2, str, sizeof(str) ));
                p2++;
            }
            break;
        }
        default:
        {
            printf("none type of address\n");
            break;
        }
    }
    return 0;
}

2.gethostbyaddr()

#include<stdio.h>
#include<netdb.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
int main(int argc, char *argv[])
{
    if(argc<2)
    {
        printf("the argc need more two\n");
        return 1;
    }
    struct hostent *host;
    const char *add = argv[1];
    char p[30];
    inet_pton(AF_INET, add, p);
    host = gethostbyaddr(p, strlen(p), AF_INET);
    printf("hostname:%s\n",host->h_name);
    return 0;
}

 

运行结果:

 

 

 

 

 

 

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值