Windows Package - How to get the external IP address in a batch file variable

I am making a program that checks if a user's IP address is a specific IP address.

I have currently created a successful internal IP version:

@echo off
set userIp=192.168.90.100
for /f "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
for /f "delims=[] tokens=2" %%a in ('ping %computername% -4 -n 1 ^| findstr "["') do set thisip=%%a
goto :Check

:Check
if %localIp%==%userIp% goto :Good
if %thisip%==%userIp% goto :Good
goto :Bad

And I'm trying to do the same thing that works with external IP addresses.

I researched online, and this is what I got so far.

@echo off
for /f "tokens=2 delims=:" %%a IN ('nslookup myip.opendns.com. resolver1.opendns.com ^| findstr /IC:"Address"') do if /i %%a=="10.11.12.13" goto :Good
goto :Bad

I need a little help on how to fix this.

Regards, djmrminer.

+4
source share
3 answers

With clean batch / existing tools:
EDIT: Modified the packet to handle IPv6 addresses correctly too

@Echo off
for /f "tokens=1* delims=: " %%A in (
  'nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL^|find "Address:"'
) Do set ExtIP=%%B
Echo External IP is : %ExtIP%

Link

Another one with PowerShell:

@Echo off
For /f %%A in (
  'powershell -command "(Invoke-Webrequest "http://api.ipify.org").content"'
) Do Set ExtIP=%%A
Echo External IP is : %ExtIP%

And another slightly different PowerShell option:

@Echo off
For /f %%A in (
  'powershell -nop -c "(Invoke-RestMethod http://ipinfo.io/json).IP"'
) Do Set ExtIP=%%A
Echo External IP is : %ExtIP%
+11

IP- , :

curl " http://api.ipify.org"

EDIT:

Windows:

for /f "tokens=3 delims== " %%A in ('
nslookup -debug myip.opendns.com. resolver1.opendns.com 2^>NUL^|findstr /C:"internet address"
') do set "ext_ip=%%A"
+3

, . .com.

-, google.com echo %a, :

" xx.xx.xx.x" !

, if !

- : if "%%a"==" xx.xx.xx.x" Goto:good .

0

Source: https://habr.com/ru/post/1780455/


All Articles