linux中gethostbyname和gethostbyaddr的使用

gethostbyname:根据主机名获取ip

gethostbyaddr:根据ip获取主机名

示例如下:

#include "net_common.h"

int main()
{
    char *name = "localhost";
    //INET_ADDRSTRLEN值为16,用来标识ipv4地址长度
    char str[INET_ADDRSTRLEN];
    //根据主机名获取ip
    struct hostent *hptr = gethostbyname(name);

    if(hptr == NULL)
    {
        hstrerror(h_errno);
    }

    //hostent中的h_addr_list是一个数组
    char **pptr = hptr->h_addr_list;
    for(; *pptr != NULL; pptr++)
    {
        //将ip保存在str中并打印。
        puts(inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
    }

    //清空结构体,以便再次使用
    memset( hptr, 0, sizeof(struct hostent));
    hptr = NULL;

    //将ip转为网络地址格式
    int nip = inet_addr(str);
    //使用gethostbyaddr需将网络地址格式的ip转为字符串类型
    hptr = gethostbyaddr((char *)&nip, INET_ADDRSTRLEN, AF_INET);


    if(hptr == NULL)
    {
        hstrerror(h_errno);
    }
    //打印主机名
    puts(hptr->h_name);

    return 0;
}

因为每次都需要写头文件,所以将一些常用的头文件整理了放在net_common.h中,内容如下:

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

//一个常用的错误检查函数
void check(char * fname)
{
        if(errno==-1)
        {
                perror(fname);
                exit(EXIT_FAILURE);
        }
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值