如何将 IP 地址获取到批处理文件变量中?

How do I get the IP address into a batch-file variable?

提问人:level42 提问时间:5/5/2011 最后编辑:indivlevel42 更新时间:8/9/2023 访问量:292536

问:

我有一个奇怪的问题,不确定它是否可能。

我想写一个脚本,例如,我将使用 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

这甚至可能吗?

批处理文件 IP

评论

2赞 Joey 5/6/2011
您可以有多个 IP 地址,大多数计算机甚至有多个 IP 地址。那么你想要哪一个呢?

答:

0赞 MealstroM 5/5/2011 #1

尝试这样的事情

echo "yours ip addresses are:"
ifconfig | grep "inet addr" | cut -d':' -f2 | cut -d' ' -f1

类似 Linux 的系统

1赞 fvu 5/5/2011 #2

假设您提到的 Windows 操作系统 i p config

如果你愿意安装一些 Unixy 实用程序,比如 grep 和 cut 的 windows-port,你可以这样做。但是,在像您使用 ipconfig 的示例中,在具有多个 NIC 或例如 VMWare 的机器中,这将是一团糟。

Powershell 可能是您想要的工具,请在此处查看示例。

评论

0赞 level42 5/5/2011
非常感谢,我一直在寻找一种非常简单的方法来执行此操作,但感谢您提供的信息
16赞 indiv 5/6/2011 #3

单独提取地址有点困难,但您可以轻松获取整个 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

评论

1赞 Sk8erPeter 11/22/2013
在 >= Windows 7 上,您应该找到字符串“IPv4 地址”(而不是“IP 地址”),因此正确的命令如下所示:.我认为你应该把它添加到你的帖子中。 :)不过,我投了赞成票,因为这是另一个好主意。:)ipconfig | findstr /R /C:"IPv4 Address.*:"
0赞 indiv 11/22/2013
@Sk8erPeter:谢谢!我已经用新的正则表达式更新了答案。
0赞 Sk8erPeter 11/23/2013
别客气!感谢您更新它。你刚才写的是一个更好的主意:)ipconfig | findstr /R /C:"IP.* Address"
1赞 Николай Мишин 5/12/2015
ipconfig | findstr /R /C:"IP.*"如果语言与英语不同,这更好
0赞 Sam Hasler 2/19/2016
在 Win7 或 XP 上仅提供 IPv4 地址:ipconfig | findstr /R /C:"^ *IP[v4]* Address"
51赞 mousio 5/6/2011 #4

这将在以下输出中打印 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
    )
)

评论

2赞 indiv 5/6/2011
我认为您需要将“IP 地址”更改为“IP 地址”,或传递到 以进行不区分大小写的匹配。/Ifindstr
0赞 mousio 5/6/2011
@indiv:正确(我有不同的语言环境,我手动更改了字符串);答案已更新...
3赞 Vik David 5/6/2011
在我的 Win7 计算机上,要匹配的字符串是“IPv4 地址”。
0赞 mousio 5/6/2011
@Vik:感谢您提及这一点,希望对其他用户有所帮助。只需在脚本中更新相应的字符串:]
1赞 Sam Hasler 2/19/2016
可以将正则表达式与 findstr 一起使用来测试任一字符串:findstr /R /C:"^ *IP[v4]* Address"
2赞 skywalkr73 7/15/2012 #5

我知道这是一篇较旧的帖子,但我在尝试解决 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 AddressIP Address

2赞 Lizz 11/4/2012 #6

使用是很好的,除非你希望除了本地主机之外,还想灵活地获取远程主机的 IP。要从类似 www.google.com 的东西中获取它,请使用 try:IPCONFIGPING

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 地址,则您的变量末尾将有一个逗号,因为每个地址都将用逗号分隔。

评论

1赞 Stephan 9/2/2013
ping localhost会给你.请改用。127.0.0.1ping %computername%
1赞 mkoertgen 8/11/2015
对我来说最好的答案。恕我直言,使用 delims=[] 过滤“pinging”似乎是最强大的。
27赞 OptekProduction 12/23/2012 #7

在 Windows 7 中:

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
pause

评论

1赞 sudheeshix 10/5/2016
感谢您摆脱前面的额外空间。:)set ip=%ip:~1%
1赞 konieckropka 5/14/2022
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
3赞 Ian 3/8/2013 #8

这是对@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
0赞 Paul McNabb 3/9/2013 #9

以下都是在 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}
0赞 Mingjiang Shi 3/21/2013 #10

下面的脚本会将 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

这篇博文中的想法。

67赞 Fabio Iotti 7/14/2013 #11

以下代码适用于自 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%  

您可以在我的博客上找到这些命令的详细说明。

评论

4赞 FelikZ 10/13/2014
它给了我一个错误:“%%a 此时是意外的。
2赞 Fabio Iotti 10/13/2014
这仅适用于批处理,您可能在命令行中运行它,对吧?
1赞 Fabio Iotti 10/14/2014
我认为这取决于命令的工作方式,以及它的威胁变化方式。我实际上无法解释为什么它不同,但是替换 with 的两种情况将使它在命令行中工作。当然,这会阻止它批量工作。FOR%%a%%a%a
1赞 Alicia 1/16/2017
谢谢,我发现这非常有用,原因有三个:1)它选择了正确的本地网络接口2)它适用于任何Windows版本,无论语言如何3)它不会在IP地址的开头提供空格。
2赞 Xdg 2/27/2018
如果您没有第二个本地接口,这很好。对我来说,它从以太网适配器 VirtualBox Host-Only Network #2 中选择 IP。当你禁用它时,没关系。
9赞 SergeyA 11/12/2013 #12

即使你有虚拟网络适配器或 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%

评论

0赞 Leeroy 7/15/2020
route print似乎是 Windows 系统更可靠、更优雅的选择。这应该是公认的答案。
1赞 script'n'code 9/24/2020
它非常接近最理想的解决方案。只是当有多个(虚拟)接口使用 0.0.0.0 时,它只存储它找到的最后一个值。根据人们使用结果数据的方式(以及特定目的),它可能是另一个人所期望的。
20赞 rightcodeatrighttime 3/13/2014 #13
@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%

评论

0赞 Rick 12/23/2014
我可以限制接口吗?
3赞 Kennet 3/7/2018
如果您有多个适配器,例如 VirtualBox、VMWare,则为最佳解决方案
1赞 herm 3/14/2018
适用于安装了 docker 的机器
0赞 herm 3/19/2018
实际上,在一台机器上,它在另一台机器上工作,它返回了 Default,所以它实际上并不可靠地工作。知道如何解决这个问题吗?
0赞 script'n'code 9/24/2020
当将多个(虚拟)接口绑定到/使用 0.0.0.0 时,此解决方案可能会产生意外的结果/值。
-3赞 Farhan Khan 11/14/2015 #14

如果您只想要 IP 地址,请尝试以下操作:

#Variable to store ip address
ipaddr=$(hostname -I)

echo "$ipaddr"

评论

1赞 jeb 11/14/2015
问题是关于 windows 批处理文件,你显示了 linux bash 的答案
0赞 Jonny_Starky 1/17/2016 #15

在 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 地址。

2赞 vkrams 2/28/2019 #16

Windows 中的一行命令获取 IP 地址。

for /F "tokens=14" %%i in ('"ipconfig | findstr IPv4"') do SET LOCAL_IP=%%i

在此命令之后,将打印 IP 地址。或者,您可以在批处理脚本中用作引用变量echo %LOCAL_IP%%LOCAL_IP%

10赞 Joshua Dyck 11/23/2019 #17

顶级域名;

在我的用例中,我无法使用上述任何答案,因此我使用以下命令来获取以太网网络适配器的 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 命令提示符中的命令进一步指定我想要的行。 在这里,我想要包含字符串的行。findstrIP 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|=^

在命令的末尾,您可以指定要与返回的内容一起运行的命令。在这种情况下,我使用它和其他一些文本一起打印出来,但您也可以将值分配给环境变量,例如,或者任何您喜欢的内容。forechodo set IP=%i

很整洁,对吧?

如果您有任何改进的想法,请发表评论。我很想听听:)或者你可以直接编辑。

评论

1赞 Joshua Dyck 6/9/2020
批处理文件对变量使用的语法略有不同:请注意,变量使用双倍百分比。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
0赞 Mark Deven 2/29/2020 #18

对于我的系统,我有许多 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
0赞 Daryn 12/15/2020 #19

如果需要 PowerShell 或 WSL2 bash:If you want PowerShell or WSL2 bash:

我只是在超级用户的基础上建立这个答案
但我发现以下选项更清晰地获取我的 LAN IP 地址:

  1. 找到你想知道的接口名称 对我来说,它是 ,
    所以
    对我来说,这个名字是 .
    (在下面的命令中替换为您的接口名称)
    Configuration for interface "Wi-Fi"Wi-Fi"Wi-Fi"

  2. PowerShell:

    $myip = netsh interface ip show address "Wi-Fi" `
      | where { $_ -match "IP Address"} `
      | %{ $_ -replace "^.*IP Address:\W*", ""}
    
    echo $myip
    

    输出:192.168.1.10

  3. 或者,我的边缘情况,在 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*//')