The Computer Oracle

Bash: lookup an IP for a host name, including /etc/hosts in search

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 Bash: Lookup An Ip For A Host Name, Including /Etc/Hosts In Search
00:39 Accepted Answer Score 25
00:55 Answer 2 Score 3
01:09 Answer 3 Score 6
01:22 Answer 4 Score 0
01:57 Thank you

--

Full question
https://superuser.com/questions/305939/b...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#linux #ubuntu #bash #dns #hostsfile

#avk47



ACCEPTED ANSWER

Score 25


getent uses the low-level glibc information functions to query all configured sources.

$ getent ahosts amd.com
163.181.249.32  STREAM amd.com
163.181.249.32  DGRAM  
163.181.249.32  RAW    
$ getent ahosts ipv6.google.com
2001:4860:b009::69 STREAM ipv6.l.google.com
2001:4860:b009::69 DGRAM  
2001:4860:b009::69 RAW    



ANSWER 2

Score 6


$ gethostip localhost
localhost 127.0.0.1 7F000001
$ gethostip -d example.org
192.0.43.10

From the syslinux package, at least in Ubuntu 12.04.




ANSWER 3

Score 3


This is super-hacky, but I've been using it for ages, and it works (for ipv4):

function ipfor() {
  ping -c 1 $1 | grep -Eo -m 1 '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
}

Use like: ipfor google.com




ANSWER 4

Score 0


I simply use the following as replacement for inapt 'host' cmd. This automatically will do the right thing with some restrictions (IPv4 only).

myhost.c:

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>

#define TOIN(a) ((struct sockaddr_in *)&(a))

main(argc, argv)
    char **argv;
{
    int err;
    struct sockaddr sa;
    char hbuf[NI_MAXHOST];

    if (argc <= 1) {
        printf("more args\n");
        exit(-1);
    }
    TOIN(sa)->sin_family = AF_INET;
    if (inet_pton(AF_INET, *(argv + 1), &TOIN(sa)->sin_addr) != 1) {
        printf("can't inet_pton: %s\n", errno ? strerror(errno) : "format err");
        exit(-1);
    }
    if (err = getnameinfo(&sa, sizeof(struct sockaddr_in), hbuf, sizeof hbuf, 0, 0, NI_NAMEREQD)) {
//        printf("%s\n", gai_strerror(err));
        printf("Host %s not found: 3(NXDOMAIN)\n", *(argv + 1));
        exit(-1);
    } else {
        printf("%s\n", hbuf);
        exit(0);
    }
}