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

题目


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

分析


1.通过目标域名获取目标IP地址对应的网络字节序(需强转为对应的类型),使用gethostbyname()函数;

2.把获取的网络字节序转换为点分十进制的IP地址(需强转为对应的类型),以便查询。

代码


/***********************************************************************************
*
*	file name:	udp_ntoh.c
*	author	 :  cnzycwp@126.com 
*	date	 :  2024/06/04
*	function :  该案例是实现解析www.baidu.com的域名,把获取到的百度的IP地址全部输出到
*               终端并验证是否正确
* 	note	 :  None
*   version  :
*
*	CopyRight (c)  2023-2024   cnzycwp@126.com   All Right Reseverd 
*
* **********************************************************************************/
/************************************头文件*****************************************/
#include <netdb.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/***********************************************************************************/
int main()
{
   
    int i = 0;       //定义一个变量,表示IP地址下标
    uint32_t ip;
    char *host_ip;

    
    //1. 获取服务器的IP地址
    struct hostent *hostent =  gethostbyname("www.baidu.com");

    //2.定义结构体获取IP地址
    struct in_addr ip_addr;

    //3.当结构题hosten->h_addr_list为空时,退出循环
    while (hostent->h_addr_list[i] != NULL)
    {
        //4. 获取IP地址对应的网络字节序
        ip = *(uint32_t*)hostent->h_addr_list[i];

        //5. 网络字节序转换为点分十进制IP地址   char *inet_ntoa(struct in_addr in);
        ip_addr = *(struct in_addr*)&ip;
        host_ip = inet_ntoa(ip_addr);

        //6. 打印结果
        printf("IP: %s\n", host_ip);

        i++;
    }
    
    return 0;
    
}

结果


image

image

posted @ 2024-06-04 19:45  陳文鹏  阅读(26)  评论(0编辑  收藏  举报