Networking – Nslookup command line with A record IP as sole output

command linecommand-line-argumentsdnsnetworking

I've found the following command to get your current public IP that works well from command line:

nslookup myip.opendns.com resolver1.opendns.com

I want to be able to run a command though that JUST prints the resulant IP. (Right now it shows the specified DNS server and it's IP along with all the other info IE:

Server:  resolver1.opendns.com
Address:  208.67.222.222

Non-authoritative answer:
Name:    myip.opendns.com
Address:  123.123.123.123

I want it to just output:
123.123.123.123

Not sure if the is a command line flag to get what I want or if I can use some command line trickery to get just the output I want (ultimately, I want to redirect the output to a file, "> filename.txt"

Best Answer

Nslookup with A record IP as sole output

Assuming you are using Windows, this can be done using a simple one line command.

From the command line:

for /f "skip=4 usebackq tokens=2" %a in (`nslookup myip.opendns.com resolver1.opendns.com`) do echo %a > ip.txt

From a batch file:

for /f "skip=4 usebackq tokens=2" %%a in (`nslookup myip.opendns.com resolver1.opendns.com`) do echo %%a > ip.txt

Notes:

  • The public IP address is stored in a file (ip.txt).
  • The above does not require non standard windows commands like PowerShell, .Net or awk.

Further Reading

Related Question