假设我在/ etc / hosts中有如下条目:
10.10.64.225主机名1
10.10.64.226主机名1
10.10.64.227 HostName1
FE80:0000:0000:0000:0202:B3FF:FE1E:8329 HostName1
2001:0db8:85a3:0000:0000:8a2e:0370:7334 HostName1
现在,我要列出同一主机名下的所有IP。
我正在使用getaddrinfo
函数。
test.c文件:
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct addrinfo hints, *list, *curr;
int arg, errcode;
if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
fprintf(stderr, " %s HOSTNAME ...\n", argv[0]);
fprintf(stderr, "\n");
return EXIT_FAILURE;
}
for (arg = 1; arg < argc; arg++) {
memset(&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
errcode = getaddrinfo(argv[arg], NULL, &hints, &list);
if (errcode) {
fprintf(stderr, "%s: %s.\n", argv[arg], gai_strerror(errcode));
return EXIT_FAILURE;
}
for (curr = list; curr != NULL; curr = curr->ai_next) {
if (curr->ai_family == AF_INET) {
char addrbuf[INET_ADDRSTRLEN + 1];
const char *addr;
addr = inet_ntop(AF_INET, &(((struct sockaddr_in *)curr->ai_addr)->sin_addr), addrbuf, sizeof addrbuf);
if (addr == NULL) {
fprintf(stderr, "%s: %s.\n", argv[arg], strerror(errno));
return EXIT_FAILURE;
}
printf("%s: IPv4 = %s\n", argv[arg], addr);
} else
if (curr->ai_family == AF_INET6) {
char addrbuf[INET6_ADDRSTRLEN + 1];
const char *addr;
addr = inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)curr->ai_addr)->sin6_addr), addrbuf, sizeof addrbuf);
if (addr == NULL) {
fprintf(stderr, "%s: %s.\n", argv[arg], strerror(errno));
return EXIT_FAILURE;
}
printf("%s: IPv6 = %s\n", argv[arg], addr);
}
}
freeaddrinfo(list);
}
return EXIT_SUCCESS;
}
输出: ./test HostName1
ks1:IPv4 = 10.10.64.225
ks1:IPv6 = FE80:0000:0000:0000:0202:B3FF:FE1E:8329
代码中的问题是,它仅返回第一个IPV4和第一个IPV6地址。 并且我需要使用相同主机名的所有IP的列表。