UDP协议的应用——域名解析

设计程序实现解析www.baidu.com 的域名,把获取到的百度的IP地址全部输出到终端并验证是否正确

/*************************************************************************************************************************
 *
 *	file name:	udp_gethostbyname.c
 *	author	 :  Dazz
 *	date	 :  2024/6/4
 *	function :  设计程序实现解析www.baidu.com的域名,把获取到的百度的IP地址全部输出到终端并验证是否正确。
 *
 *
 *	CopyRight (c)  2024   Dazz_24@163.com   All Right Reseverd
 *
 * **************************************************************************************************************************/
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

 int main(int argc, char const *argv[])
{
       // 检查参数有效性
    if (argc != 2)
    {
        fprintf(stderr, "argument is invaild ,errno:%d,%s\n", errno, strerror(errno));
        exit(1);
    }
	
	int cnt = 0;

    //使用 gethostbyname函数解析域名
	struct hostent *p = gethostbyname(argv[1]);

    //循环遍历>h_addr_list数组
	while (((struct in_addr **)p->h_addr_list)[cnt] != NULL)
    {
        printf("%s\n", inet_ntoa(*(struct in_addr *)(p->h_addr_list)[cnt]));
        // char *inet_ntoa(struct in_addr in);

        cnt++;
    }

    return 0;
}

运行结果:
image

posted @ 2024-06-04 20:17  Dazz_24  阅读(45)  评论(1)    收藏  举报