C写一个DNS解析域名
时间: 2024-03-10 22:47:21 浏览: 36
以下是一个使用C语言编写的DNS解析域名的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
struct hostent *he;
struct in_addr **addr_list;
int i;
if (argc != 2) {
fprintf(stderr, "Usage: %s hostname\n", argv[0]);
exit(1);
}
if ((he = gethostbyname(argv[1])) == NULL) {
herror("gethostbyname");
exit(1);
}
printf("Official name: %s\n", he->h_name);
for (i = 0; he->h_aliases[i] != NULL; i++) {
printf("Alias: %s\n", he->h_aliases[i]);
}
addr_list = (struct in_addr **) he->h_addr_list;
for (i = 0; addr_list[i] != NULL; i++) {
printf("IP address: %s\n", inet_ntoa(*addr_list[i]));
}
return 0;
}
```
该程序使用gethostbyname函数解析指定的主机名,并打印出它的官方名称、别名和IP地址。需要注意的是,gethostbyname函数在多线程环境下不是线程安全的,建议使用getaddrinfo函数代替。