Last active
December 23, 2015 06:09
-
-
Save masami256/6592191 to your computer and use it in GitHub Desktop.
getaddrinfo(3) と getnameinfo(3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
enum { | |
Ip2Addr = 0, | |
Addr2Ip, | |
}; | |
static void | |
ip2host(const char *target) | |
{ | |
struct sockaddr_in sa = { 0 }; | |
char buf[NI_MAXHOST] = { 0 }; | |
int ret = 0; | |
sa.sin_family = AF_INET; | |
inet_pton(sa.sin_family, target, &sa.sin_addr); | |
ret = getnameinfo((const struct sockaddr *) &sa, sizeof(sa), buf, sizeof(buf), NULL, 0, NI_NAMEREQD); | |
if (ret != 0) { | |
printf("[-]Error %s\n", gai_strerror(ret)); | |
exit(-1); | |
} | |
printf("%s -> %s\n", target, buf); | |
} | |
static void | |
host2ip(const char *target) | |
{ | |
struct addrinfo *result = NULL; | |
struct addrinfo hints = { 0 }; | |
struct addrinfo *info = NULL; | |
int ret = 0; | |
hints.ai_socktype = SOCK_STREAM; | |
ret = getaddrinfo(target, NULL, &hints, &result); | |
if (ret != 0) { | |
printf("[-]Error %s\n", gai_strerror(ret)); | |
exit(-1); | |
} | |
for (info = result; info != NULL; info = info->ai_next) { | |
char buf[INET_ADDRSTRLEN] = { 0 }; | |
struct in_addr ia; | |
ia.s_addr = ((struct sockaddr_in *)(info->ai_addr))->sin_addr.s_addr; | |
inet_ntop(info->ai_family, &ia, buf, sizeof(buf)); | |
printf("%s -> %s\n", target, buf); | |
} | |
freeaddrinfo(result); | |
} | |
static void | |
usage(const char *progname) | |
{ | |
fprintf(stderr, "usage %s [-ih] host/addr\n", progname); | |
exit(-1); | |
} | |
int | |
main(int argc, char **argv) | |
{ | |
int flag = Ip2Addr; | |
char *target = NULL; | |
if (argc != 3) | |
usage(argv[0]); | |
if (!strcmp(argv[1], "-i")) | |
flag = Ip2Addr; | |
else if (!strcmp(argv[1], "-h")) | |
flag = Addr2Ip; | |
else | |
usage(argv[0]); | |
target = argv[2]; | |
if (flag == Ip2Addr) | |
ip2host(target); | |
else | |
host2ip(target); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment