Analysis the domain name of Baidu (V2)

/*********************************************************************************************************
 *  file name:   hw.c
 *  author   :   wvjnuhhail@sina.cn
 *  data     :   2024/06/04
 *  function :   设计程序实现解析www.baidu.com的域名,把获取到的百度的IP地址全部输出到终端并验证是否正确。
 *  note     :   None
 *  version  :   Version2
 *
 *  CopyRight (c) 2023-2024     All Right Reseverd
 *
 * ******************************************************************************************************/

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <netdb.h>
#include <sys/socket.h>

int main(int argc, char const *argv[])
{
  // gethostbyname句柄类型为struct hostent *
  struct hostent *myHW;

  int cnt = 0;

  // 获取百度的ip地址
  myHW = gethostbyname(argv[1]);
  /*struct hostent *gethostbyname(const char *name);*/

  while ((myHW->h_aliases)[cnt] != NULL)
  {
    printf("%s\n", (myHW->h_aliases)[cnt]);

    cnt++;
  }

  if (myHW)
  {
    int i = 0; // ip地址的下标

    // myHW->h_addr_list[i]循环直至NULL,退出循环
    while (myHW->h_addr_list[i])
    {
      // 获取ip转化为网络字节序,网络字节序再转化为ip地址
      struct in_addr *addr = (struct in_addr *)myHW->h_addr_list[i];

      printf("%sIP is : %s\n", argv[1], inet_ntoa(*addr));

      i++;
    }
  }
  else
  {
    perror("Unable analysis domain name\n");
  }

  return 0;
}

编译运行
image

posted @ 2024-06-04 21:42  WJnuHhail  阅读(3)  评论(0编辑  收藏  举报