diff options
author | 53hornet <53hornet@gmail.com> | 2019-02-02 22:59:54 -0500 |
---|---|---|
committer | 53hornet <53hornet@gmail.com> | 2019-02-02 22:59:54 -0500 |
commit | 379c2c17e68d5d471a6a9673b7e9cd1fb9d99bbb (patch) | |
tree | eed499da8211a5eece757639331a2d82bce4fa4c /pgm4/inet_addrs.d/gethost.c | |
download | csci415-379c2c17e68d5d471a6a9673b7e9cd1fb9d99bbb.tar.xz csci415-379c2c17e68d5d471a6a9673b7e9cd1fb9d99bbb.zip |
Diffstat (limited to 'pgm4/inet_addrs.d/gethost.c')
-rw-r--r-- | pgm4/inet_addrs.d/gethost.c | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/pgm4/inet_addrs.d/gethost.c b/pgm4/inet_addrs.d/gethost.c new file mode 100644 index 0000000..dcfc7fd --- /dev/null +++ b/pgm4/inet_addrs.d/gethost.c @@ -0,0 +1,57 @@ +// Using getnameinfo() to get host name for a +// given IP address (argv[1]). +// +// P. Kearns, February 2009 + +#include <netdb.h> +#include <sys/socket.h> +#include <arpa/inet.h> +#include <netinet/in.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> + +int main(int argc, char **argv) +{ + + int ecode; + struct in_addr fillin; + struct sockaddr_in addr; + char host[NI_MAXHOST]; + + if (argc != 2) { + fprintf(stderr,"usage: gethost address\n"); + exit(1); + } + +// Dotted decimal to binary IP address. + + ecode = inet_pton(AF_INET, argv[1], &fillin); + if (ecode == 0) { + fprintf(stderr,"inet_pton: invalid address\n"); + exit(1); + } + if (ecode < 0) { + perror("inet_pton"); exit(1); + exit(1); + } + +// Fill in blanks of a sockaddr_in after zeroing it out. + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(0); + memcpy(&(addr.sin_addr), &fillin, sizeof(addr.sin_addr)); + +// Do the lookup. + + ecode = getnameinfo((struct sockaddr *) &addr, sizeof(addr), + host, NI_MAXHOST, NULL, 0, NI_NAMEREQD); + if (ecode) { + fprintf(stderr, "getnameinfo: %s\n", gai_strerror(ecode)); + exit(1); + } + + printf("Hostname: %s\n", host); + exit(0); +} |