16

I'd like to know how to extract just the IP address from a DNS / dig query. The query I'm running looks like this:

lab-1:/var/# dig +answer smtp.mydomain.net +short   
smtp.ggs.mydomain.net
10.11.11.11

I'd like to be able to get just the IP address returned. I'm currently playing around with the bash pipe and the awk command. But so far, nothing I've tried is working.

Thanks.

6
  • 5
    drop +answer use just +short
    – man0v
    Feb 26, 2018 at 14:16
  • that doesn't work. still gives me the same results @man0v
    – dot
    Feb 26, 2018 at 14:18
  • weird, it works for me on centos.. wonder what version of dig you are using? What distro(or os)?
    – man0v
    Feb 26, 2018 at 14:19
  • 1
    @dot post dig version too. Use dig -v
    – Patrick
    Feb 26, 2018 at 14:26
  • 1
    Is smtp.mydomain.net an alias for smtp.ggs.mydomain.net?
    – ctx
    Feb 26, 2018 at 14:31

2 Answers 2

22

I believe dig +short outputs two lines for you because the domain you query, smtp.mydomain.net is a CNAME for smtp.ggs.mydomain.net, and dig prints the intermediate resolution step.

You can probably rely on the last line from dig's output being the IP you want, though, and therefore the following should do:

dig +short smtp.mydomain.net | tail -n1
1
  • 1
    What if it returns 2 IPs (2 A records)?
    – Matt White
    Nov 19, 2021 at 21:29
7

@dhag's answer sounds good; if you do not want to “rely on the last line from dig's output being the IP” you can use grep to extract just the numerical IP address:

dig +short smtp.mydomain.net | grep '^[.0-9]*$'
1
  • @JordanBrough No, it doesn't
    – annahri
    May 31, 2020 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.