简体   繁体   English

Windows Batch - 如何将外部 IP 放入批处理文件变量中

[英]Windows Batch - How to get the external IP into a batch-file variable

I am making a program that checks if a user's IP is a certain IP address.我正在制作一个程序来检查用户的 IP 是否是某个 IP 地址。

Currently, I created a successful internal IP version:目前,我创建了一个成功的内部 IP 版本:

@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 am trying to make the same thing that works with external IPs.我正在尝试制作与外部 IP 相同的东西。

I researched online, and here 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 bit of help on how to fix this.我需要一些关于如何解决这个问题的帮助。

With pure batch/already present tools:使用纯批处理/已经存在的工具:
EDIT: changed the batch to properly handle also IPv6 addresses编辑:更改批处理以正确处理 IPv6 地址

@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%

Reference参考

Another one with powershell:另一个带有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 variant:另一个稍微不同的 powershell 变体:

@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%

To get your public IP without additional parsing do this:要在不进行额外解析的情况下获取您的公共 IP,请执行以下操作:

curl " http://api.ipify.org "卷曲“ http://api.ipify.org

EDIT:编辑:

This version is more reliable across windows language versions:此版本在 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"

First it seems there is a .首先似乎有一个. too much after the first .com .第一次.com后太多了。

Second when using your command with simply google.com and echo %a I get the following:其次,当使用您的命令与google.comecho %a我得到以下信息:

" xx.xx.xx.x" without the quotes and with two leading spaces! " xx.xx.xx.x"没有引号和两个前导空格!

So your if will never be true!所以你的 if永远不会是真的!

Change it to something like this: if "%%a"==" xx.xx.xx.x" Goto:good and you should be fine.把它if "%%a"==" xx.xx.xx.x" Goto:good这样: if "%%a"==" xx.xx.xx.x" Goto:good你应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM