域名解析(Domain Name Resolution)是将人类可读的域名转换为计算机可识别的IP地址的过程。C语言提供了多种方法来进行域名解析,主要包括使用标准库函数getaddrinfo
和gethostbyname
。
getaddrinfo
:/etc/hosts
)。gethostbyname
:getaddrinfo
进行正向解析#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s hostname\n", argv[0]);
exit(EXIT_FAILURE);
}
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 1;
}
printf("IP addresses for %s:\n", argv[1]);
for (p = res; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // free the linked list
return 0;
}
gethostbyname
进行正向解析#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s hostname\n", argv[0]);
exit(EXIT_FAILURE);
}
struct hostent *host = gethostbyname(argv[1]);
if (host == NULL) {
perror("gethostbyname");
exit(EXIT_FAILURE);
}
struct in_addr **addr_list = (struct in_addr **)host->h_addr_list;
for (int i = 0; addr_list[i] != NULL; i++) {
printf("IP address: %s\n", inet_ntoa(*addr_list[i]));
}
return 0;
}
getaddrinfo
返回错误原因:
解决方法:
gethostbyname
返回NULL原因:
解决方法:
希望这些信息对你有所帮助!
高校公开课
Elastic 中国开发者大会
云+社区技术沙龙[第27期]
腾讯技术创作特训营第二季第2期
技术创作101训练营
TC-Day
TC-Day
领取专属 10元无门槛券
手把手带您无忧上云