Nslookup command line with A record IP as sole output
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
orawk
.
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- for /f - Loop command against the results of another command.
- nslookup - Lookup IP addresses on a NameServer.
nslookup
was never really intended for scripted use. You really want to use dig
instead, which with the +short
option produces machine-readable output according to the query parameters.
dig +short myip.opendns.com @resolver1.opendns.com
This is a good usecase for awk.
nslookup myip.opendns.com resolver1.opendns.com | awk -F': ' 'NR==6 { print $2 } '
Here we are piping to awk, delimiting by ": " and then only outputting the second delimited field of line 6.
If you're on Windows, and have PowerShell installed (v1 or better) (and a .Net version) you could use a (long) one-liner like this:
[System.Net.Dns]::GetHostAddresses("www.google.com")[0] | Select IPAddressToString -ExpandProperty IPAddressToString | Out-File c:\folder\filename.txt
This will lookup www.google.com and put the first returned IPv4 address into a file.
If you're using PowerShell v3+ on Windows 8+ (or Server 2012+) you can user the use the Resolve-DnsName
cmdlet instead of the .Net GetHostAddress call. ie:
(Resolve-DnsName www.google.com)[0] | Select IPAddressToString -ExpandProperty IPAddressToString | Out-File c:\folder\filename.txt
Simply change www.google.com to your preferred domain name. Or put it in a PowerShell script and set it up to accept an argument (of the domain name you want to look up).
More info on that: How to pass an argument to a PowerShell script?
Works good for me on my Linux machine. I've never tried it on other systems though but Google has a lot of articles on how to install dig
for example on Windows
The only thing to note, for local hostnames search domain should be added explicitly.
So if you have myhost
host in your local network with search domain mynetwork
put
dig +short myhost.mynetwork
on command line.
Examples:
sergeyi@sergeyi:~$ dig +short google.ru
173.194.222.94
sergeyi@sergeyi:~$ dig A +short google.ru
173.194.222.94
sergeyi@sergeyi:~$ dig AAAA +short google.ru
2a00:1450:4010:c0b::5e