0

I try to use name resolution and get IP address of a web site. I used nslookup command and use 6'th line of its output. Because I noticed that output of nslookup contains IP address(in IPv4) in 6'th line. My command was :

website=<somewebsiteURL>
IP=$(nslookup "$website" | head -n 6 | tail -n 1 | cut -d" " -f2)

Also I tried sed command to reach the same goal and used :

website=<somewebsiteURL>
IP=$(nslookup "$website" | sed -n 6p | cut -d" " -f2)

result was the same, result is unreliable, sometimes worked, sometimes not.

It works correctly but not always. Sometimes it reads the 7'th line, not the 6'th line and fails.

Actually I solved my problem using another approach :

website=<somewebsiteURL>
newIP=$(nslookup "$website" | grep "Address: " | head -n 1 | cut -d" " -f2)

which gave the correct line and IP address everytime(although it can give more than one IP > nslookup can return more than one IP)

Why do the first two codes fail?

  • 3
    As you notice, the output of nslookup doesn't make a guarantee on line numbers. So, that's why it fails: you're assuming you can assume something about number of lines always being the same, but that's a wrong assumption. – Marcus Müller Feb 11 '22 at 17:48
  • The `host` output be easier to parse. – Frédéric Loyer Feb 11 '22 at 18:06

2 Answers2

0

You can give a chance to host command. As generally more than one IP can be associated with a host name, you will probably happy with the first one.

host -4 cnn.com | sed 1q  | awk '{ print $NF }'
151.101.129.67

This seems to be more reliable

sed 1q filters out all lines except for the 1st, awk '{ print $NF }' prints out the last field which is IP you want, and -4 instructs to use ipV4 address, you probably want that

Tagwint
  • 2,410
  • 1
  • 13
  • 22
0

Use grep to parse strings that "looks like" a valid IPv4 addresses :

nslookup unix.stackexchange.com | grep -Eo '([0-9]{1,3}[.]){3}[0-9]{1,3}[^#]'
151.101.129.69
151.101.1.69
151.101.193.69
151.101.65.69

Use tool such as dig. It can output directly the info you desire without the need for external parsing tool:

dig +short A unix.stackexchange.com
151.101.65.69
151.101.129.69
151.101.193.69
151.101.1.69
DanieleGrassini
  • 2,769
  • 5
  • 17