提问人:level42 提问时间:5/5/2011 最后编辑:indivlevel42 更新时间:8/9/2023 访问量:292536
如何将 IP 地址获取到批处理文件变量中?
How do I get the IP address into a batch-file variable?
问:
我有一个奇怪的问题,不确定它是否可能。
我想写一个脚本,例如,我将使用 ipconfig 作为我的命令。
现在,当您通常运行此命令时,会有大量输出。
例如,我想要的是一个仅显示 IP 地址的脚本。
echo Network Connection Test
ipconfig <---This would run in the background
echo Your IP Address is: (INSERT IP ADDRESS HERE)
输出将是
Network Connection Test
Your IP Address is: 192.168.1.1
这甚至可能吗?
答:
尝试这样的事情
echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1
类似 Linux 的系统
假设您提到的 Windows 操作系统 i p config
如果你愿意安装一些 Unixy 实用程序,比如 grep 和 cut 的 windows-port,你可以这样做。但是,在像您使用 ipconfig 的示例中,在具有多个 NIC 或例如 VMWare 的机器中,这将是一团糟。
Powershell 可能是您想要的工具,请在此处查看示例。
评论
单独提取地址有点困难,但您可以轻松获取整个 IP 地址行。
要显示任何英语 Windows 操作系统上的所有 IP 地址:
ipconfig | findstr /R /C:"IP.* Address"
要在 Windows 7+ 上仅显示 IPv4 或 IPv6 地址:
ipconfig | findstr /R /C:"IPv4 Address"
ipconfig | findstr /R /C:"IPv6 Address"
下面是具有 3 个网络适配器的 XP 计算机的一些示例输出。
IP Address. . . . . . . . . . . . : 192.168.1.10
IP Address. . . . . . . . . . . . : 10.6.102.205
IP Address. . . . . . . . . . . . : 192.168.56.1
评论
ipconfig | findstr /R /C:"IPv4 Address.*:"
ipconfig | findstr /R /C:"IP.* Address"
ipconfig | findstr /R /C:"IP.*"
如果语言与英语不同,这更好
ipconfig | findstr /R /C:"^ *IP[v4]* Address"
这将在以下输出中打印 IP 地址:ipconfig
@echo off
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
echo Network Connection Test
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do echo Your IP Address is: %%f
要仅打印第一个 IP 地址,只需在回显后添加(或另一个标签以跳转到而不是 ),或以更易读的形式:goto :eof
:eof
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
echo Your IP Address is: %%f
goto :eof
)
一种更可配置的方法是实际解析一点位的输出,这样您甚至可以指定所需的 IP 地址的适配器:ipconfig /all
@echo off
setlocal enabledelayedexpansion
::just a sample adapter here:
set "adapter=Ethernet adapter VirtualBox Host-Only Network"
set adapterfound=false
echo Network Connection Test
for /f "usebackq tokens=1-2 delims=:" %%f in (`ipconfig /all`) do (
set "item=%%f"
if /i "!item!"=="!adapter!" (
set adapterfound=true
) else if not "!item!"=="!item:IP Address=!" if "!adapterfound!"=="true" (
echo Your IP Address is: %%g
set adapterfound=false
)
)
评论
/I
findstr
findstr /R /C:"^ *IP[v4]* Address"
我知道这是一篇较旧的帖子,但我在尝试解决 vbscript 中的相同问题时遇到了这个问题。我还没有用多个网络适配器对此进行测试,但希望它仍然有帮助。
for /f "delims=: tokens=2" %%a in ('ipconfig ^| findstr /R /C:"IPv4 Address"') do (set tempip=%%a)
set tempip=%tempip: =%
echo %tempip%
这假定 Win7。对于 XP,请替换为 .IPv4 Address
IP Address
使用是很好的,除非你希望除了本地主机之外,还想灵活地获取远程主机的 IP。要从类似 www.google.com 的东西中获取它,请使用 try:IPCONFIG
PING
for /f "tokens=2 delims=[]" %%f in ('ping -4 -n 1 www.google.com ^|find /i "pinging"') do echo IP=%%f
该示例的结果是:
IP=173.194.73.106
若要获取本地主机的第一个 IP,请将“www.google.com”替换为不带引号的“%computername%”。请注意,前面的“-4”将始终获取 IPv4 地址,而不是可能的 IPv6 地址。根据需要省略。另请注意,此技术不能获取多个 IP 地址。如果这是您的目标,则需要将 NSLOOKUP 与一些额外的代码一起使用。
请注意,如果您使用 NSLOOKUP 而不是 PING,并且主机有多个 IP 地址,则您的变量末尾将有一个逗号,因为每个地址都将用逗号分隔。
评论
ping localhost
会给你.请改用。127.0.0.1
ping %computername%
在 Windows 7 中:
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
pause
评论
set ip=%ip:~1%
for /f "tokens=14 delims= " %%a in ('ipconfig^|find "IPv4"') do set ip=%%a
这将是使用“空格”而不是冒号“:”作为分隔符的较短版本,以获取最后一个空格之后的所有内容作为结果变量 %ip% 它是如何工作的?ipconfig^ | find “IPv4” 的示例结果为:.有 13 个空格,因此我们设置 tokens=14 并将此标记 %a 分配给变量 ip,没有不必要的空格。@sudheeshix @optekproductionsIPv4 Address. . . . . . . . . . . : 127.0.0.1
这是对@mousio回答的修改。我的网络连接不是持久的,因此如果 ipconfig 中缺少字符串“IPv4 地址”,则会显示下一个适配器的 IP 地址。ipconfig 的结果在适配器之间有 2 个空格。找到适配器后,在“IPv4 地址”文本之前出现 2 个空行,它假定它丢失了。仅在 Windows 7 64 位上测试。
处理 @dbenham 答案中的空行:DOS batch FOR 循环与 FIND.exe 是剥离空行吗?
@echo off
rem --- complete adapter name to find without the ending ":" ---
set adapter=Wireless LAN adapter Wireless Network Connection
rem --- token under an adapter to extract IP address from ---
set IPAddrToken=IPv4 Address
setlocal enableextensions enabledelayedexpansion
set adapterfound=false
set emptylines=0
set ipaddress=
for /f "usebackq tokens=1-3 delims=:" %%e in (`ipconfig ^| findstr /n "^"`) do (
set "item=%%f"
if /i "!item!"=="!adapter!" (
set adapterfound=true
set emptylines=0
) else if not "!item!"=="" if not "!item!"=="!item:%IPAddrToken%=!" if "!adapterfound!"=="true" (
@rem "!item:%IPAddrToken%=!" --> item with "IPv4 Address" removed
set ipaddress=%%g
goto :result
)
if "%%f-%%g-!adapterfound!-!emptylines!"=="--true-1" (
@rem 2nd blank line after adapter found
goto :result
)
if "%%f-%%g-!adapterfound!-!emptylines!"=="--true-0" (
@rem 1st blank line after adapter found
set emptylines=1
)
)
endlocal
:result
echo %adapter%
echo.
if not "%ipaddress%"=="" (
echo %IPAddrToken% =%ipaddress%
) else (
if "%adapterfound%"=="true" (
echo %IPAddrToken% Not Found
) else (
echo Adapter Not Found
)
)
echo.
pause
以下都是在 Windows XP 机器上的 cygwin 中完成的。
这将获取您的 IP 地址。请注意,hostname 命令周围有反引号,而不是单引号。
ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f 1 -d ":"
这将获取您的子网。
ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f "1 2 3" -d "."
下面将列出本地网络上的所有主机(将其放入名为“netmap”的脚本中)。我采用了上面的子网行,并将其放入名为“getsubnet”的可执行文件中,然后我从以下脚本中调用了它。
MINADDR=0
MAXADDR=255
SUBNET=`getsubnet`
hostcnt=0
echo Pinging all addresses in ${SUBNET}.${MINADDR}-${MAXADDR}
for i in `seq $MINADDR $MAXADDR`; do
addr=${SUBNET}.$i
ping -n 1 -w 0 $addr > /dev/null
if [ $? -ne 1 ]
then
echo $addr UP
hostcnt=$((hostcnt+1))
fi
done
echo Found $hostcnt hosts on subnet ${SUBNET}.${MINADDR}-${MAXADDR}
下面的脚本会将 ip 地址存储到变量 ip_address
@echo off
call :get_ip_address
echo %ip_address%
goto :eof
REM
REM get the ip address
REM
:get_ip_address
FOR /f "tokens=1 delims=:" %%d IN ('ping %computername% -4 -n 1 ^| find /i "reply"') do (FOR /F "tokens=3 delims= " %%g IN ("%%d") DO set ip_address=%%g)
goto :eof
这篇博文中的想法。
以下代码适用于自 Windows XP 以来任何平台的任何区域设置,它从(或多或少)随机的网卡中查找网络 IP。它永远不会超过几毫秒。
for /f "delims=[] tokens=2" %%a in ('ping -4 -n 1 %ComputerName% ^| findstr [') do set NetworkIP=%%a
echo Network IP: %NetworkIP%
以下方法将查找公共 IP,并在 Windows 7 和更新的计算机上工作。
for /f %%a in ('powershell Invoke-RestMethod api.ipify.org') do set PublicIP=%%a
echo Public IP: %PublicIP%
您可以在我的博客上找到这些命令的详细说明。
评论
FOR
%%a
%%a
%a
即使你有虚拟网络适配器或 VPN 连接,这也有效:This work even if you have a virtual network adapters or VPN connections:
FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%
评论
route print
似乎是 Windows 系统更可靠、更优雅的选择。这应该是公认的答案。
@echo off
FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%
评论
如果您只想要 IP 地址,请尝试以下操作:
#Variable to store ip address
ipaddr=$(hostname -I)
echo "$ipaddr"
评论
在 linux 环境下:
ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)"
或
ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)" | echo $ip
FreeBSD 中的示例:
ifconfig re0 | grep -v "inet6" | grep -i "inet" | awk '{print $2}'
如果配置了多个 IP 地址,则 stdout 中将有多个 IP 地址。
Windows 中的一行命令获取 IP 地址。
for /F "tokens=14" %%i in ('"ipconfig | findstr IPv4"') do SET LOCAL_IP=%%i
在此命令之后,将打印 IP 地址。或者,您可以在批处理脚本中用作引用变量echo %LOCAL_IP%
%LOCAL_IP%
顶级域名;
在我的用例中,我无法使用上述任何答案,因此我使用以下命令来获取以太网网络适配器的 IP 地址并按照上述问题所述回显它。
在命令行中:
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do echo Your IP Address is: %i
或者在批处理文件中:
for /f "tokens=3 delims=: " %%i in ('netsh interface ip show config name^="Wi-Fi" ^| findstr "IP Address" ^| findstr [0-9]') do set IP=%%i
对于那些想知道这一切意味着什么的人,请继续阅读
例如,大多数命令只打印出您的所有 IP 地址,我需要一个特定的 IP 地址,就我而言,该地址用于我的以太网网络适配器。ipconfig
可以使用该命令查看网络适配器列表。大多数人需要Wi-Fi或以太网。netsh interface ipv4 show interfaces
你将在命令提示符的输出中看到如下所示的表:You'll see a table like so in the output to the command prompt:
Idx Met MTU State Name
--- ---------- ---------- ------------ ---------------------------
1 75 4294967295 connected Loopback Pseudo-Interface 1
15 25 1500 connected Ethernet
17 5000 1500 connected vEthernet (Default Switch)
32 15 1500 connected vEthernet (DockerNAT)
在名称列中,您应该找到所需的网络适配器(即以太网、Wi-Fi 等)。
如前所述,我对我的案子很感兴趣。Ethernet
若要获取该适配器的 IP,可以使用 netsh 命令:
netsh interface ip show config name="Ethernet"
这给了我们这个输出:
Configuration for interface "Ethernet"
DHCP enabled: Yes
IP Address: 169.252.27.59
Subnet Prefix: 169.252.0.0/16 (mask 255.255.0.0)
InterfaceMetric: 25
DNS servers configured through DHCP: None
Register with which suffix: Primary only
WINS servers configured through DHCP: None
(出于安全原因😉,我伪造了上面的实际IP号码)
我可以使用 ms-dos 命令提示符中的命令进一步指定我想要的行。
在这里,我想要包含字符串的行。findstr
IP Address
netsh interface ip show config name="Ethernet" | findstr "IP Address"
这将给出以下输出:
IP Address: 169.252.27.59
然后,我可以使用允许我解析文件(在本例中为多行字符串)的命令,并根据分隔符和我感兴趣的项目编号拆分字符串的内容。for
请注意,我正在寻找第三项 (tokens=3),并且我使用空格字符 和 作为分隔符 ()。:
delims=:
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do echo Your IP Address is: %i
循环中的每个值或标记都作为变量 %i 打印出来,但我只对第三个“标记”或项目感兴趣(因此)。请注意,我必须转义并使用tokens=3
|
=
^
在命令的末尾,您可以指定要与返回的内容一起运行的命令。在这种情况下,我使用它和其他一些文本一起打印出来,但您也可以将值分配给环境变量,例如,或者任何您喜欢的内容。for
echo
do set IP=%i
很整洁,对吧?
如果您有任何改进的想法,请发表评论。我很想听听:)或者你可以直接编辑。
评论
for /f "tokens=3 delims=: " %%i in ('netsh interface ip show config name^="Wi-Fi" ^| findstr "IP Address" ^| findstr [0-9]') do set IP=%%i
对于我的系统,我有许多 IPv4 地址,其中只有一个是正确的。整理和检查的简单方法如下:
for /f "tokens=1,2* delims=:" %%A in ('ipconfig ^| find "IPv4 Address"') do (
set "tempip=%%~B"
set "tempip=!tempip: =!"
ping !tempip! -n 1 -w 50
if !errorlevel!==0 (
set localip=!tempip!
goto foundlocal
)
)
:foundlocal
如果需要 PowerShell 或 WSL2 bash:If you want PowerShell or WSL2 bash:
我只是在超级用户的基础上建立这个答案,
但我发现以下选项更清晰地获取我的 LAN IP 地址:
找到你想知道的接口名称 对我来说,它是 ,
所以
对我来说,这个名字是 .
(在下面的命令中替换为您的接口名称)Configuration for interface "Wi-Fi"
Wi-Fi
"Wi-Fi"
PowerShell:
$myip = netsh interface ip show address "Wi-Fi" ` | where { $_ -match "IP Address"} ` | %{ $_ -replace "^.*IP Address:\W*", ""} echo $myip
输出:
192.168.1.10
或者,我的边缘情况,在 WSL2 中执行命令:
netsh.exe interface ip show address "Wi-Fi" \ | grep 'IP Address' \ | sed -r 's/^.*IP Address:\W*//' # e.g. export REACT_NATIVE_PACKAGER_HOSTNAME=$(netsh.exe interface ip show address "Wi-Fi" \ | grep 'IP Address' \ | sed -r 's/^.*IP Address:\W*//')
评论