DNS2IP 练习
使用函数输出一个域名所对应的所有ip地址
/**************************************************************************
*
* 设计程序,获取输入的域名的所有IP地址,并显示在终端
* author:jindouliu2024@163.com
* date:2025.5.15
* notice:argv[1]:域名
* Copyright (c) 2024-2025 jindouliu2024@163.com All right Reserved
* *************************************************************************/
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<sys/socket.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <hostname>\n", argv[0]);
return 1;
}
struct hostent *p = gethostbyname(argv[1]);
if (p == NULL) {
fprintf(stderr, "gethostbyname error: %s\n", hstrerror(h_errno));
return 1;
}
int cnt = 0;
while (p->h_addr_list[cnt] != NULL) {
struct in_addr addr;
memcpy(&addr, p->h_addr_list[cnt], sizeof(struct in_addr)); // 将地址复制到struct in_addr
printf("%s\n", inet_ntoa(addr)); // 正确使用inet_ntoa
cnt++;
}
return 0;
}
浙公网安备 33010602011771号