域名解析

C语言编写:UDP协议的应用:DNS(Domain Name System)服务

将域名解析出一个或多个IP地址

查看man 手册:man 3 gethostbyname

函数原型:

  #include <netdb.h>
   extern int h_errno;
	struct hostent *gethostbyname(const char *name);
   //参数为域名
   返回值是一个地址,指向存储 struct hostent类型的空间
              struct hostent {
               char  *h_name;            /* official name of host */
               char **h_aliases;         /* alias list */
               int    h_addrtype;        /* host address type */
               int    h_length;          /* length of address */
               char **h_addr_list;       /* list of addresses */
           }
           #define h_addr h_addr_list[0] /* for backward compatibility */
//所以我们知道域名对应的IP地址在成员 h_addr_list 数组中,访问该成员就可以得到地址

程序实现:

/********************************************************************************************
*   file name: dns.c
*   author   : liaojx2016@126.com
*   date     : 2024/06/04
*   function : 将域名解析出一个或多个IP地址
*   note     : None
*
*   CopyRight (c)  2023-2024   liaojx2016@126.com   All Right Reseverd 
*
*********************************************************************************************/
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define DNS_NAME "www.baidu.com"        //待解析的域名

int main(int argc, char const *argv[])
{
    //定义变量p,并申请内存
    //  struct hostent *p = malloc(sizeof(struct hostent));
    //  if (p == NULL)
    //  {
    //     fprintf(stderr,"malloc error,error num= %d,%s\n",errno,strerror(errno));
    //     exit(1);
    //  }
    //解析域名,用变量p来接受域名解析出来的信息
     struct hostent *p = gethostbyname(DNS_NAME);
     if (p == NULL)
     {
        fprintf(stderr,"malloc error,error num= %d,%s\n",errno,strerror(errno));
        exit(1);
     }
    struct in_addr in;
    int cnt = 0;
    char addr[32];
    //遍历输出域名的IP地址
    while (p->h_addr_list[cnt] != NULL)
    {
        //从结构体中提取地址列表的每一个元素
        in.s_addr =*((uint32_t*)p->h_addr_list[cnt]);    
        // 将主机信息中的网络字节序转换成本地字节序IP
        strcpy(addr,inet_ntoa(in)); 
        printf("the ip is %s\n",addr);
        printf("%s\n",inet_ntoa( *(struct in_addr*)p->h_addr_list[cnt] ));
        bzero(addr,sizeof(addr));
        cnt++;
    }
    return 0;
}

结果:

the ip is 183.2.172.185
the ip is 183.2.172.42
posted @ 2024-06-04 21:41  沉舟道人  阅读(6)  评论(0编辑  收藏  举报