如何从 ipconfig 的输出中提取 IPv4 IP 地址
我读了这篇文章,它非常有帮助。我只是想知道是否有一种方法可以只提取 IP 地址 (xxx.xxx.xxx.xxx)。我能想到的最好的方法是使用记事本查找全部/替换全部。
有没有可以通过命令行使用的方法?
答案1
如何从 ipconfig 的输出中仅提取 IP4 地址列表?
使用以下批处理文件(test.cmd):
@echo off
setlocal
setlocal enabledelayedexpansion
for /f "usebackq tokens=2 delims=:" %%a in (`ipconfig ^| findstr /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"`) do (
set _temp=%%a
rem remove leading space
set _ipaddress=!_temp:~1!
echo !_ipaddress!
)
endlocal
使用示例和输出:
> ipconfig | findstr /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"
IPv4 Address. . . . . . . . . . . : 192.168.42.78
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.42.129
> test
192.168.42.78
255.255.255.0
192.168.42.129
进一步阅读
答案2
@echo off
setlocal
setlocal enabledelayedexpansion
rem throw away everything except the IPv4 address line
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr IPv4`) do (
rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78"
rem split on ':' and get 2nd token
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
rem we have " 192.168.42.78"
rem split on '.' and get 4 tokens (octets)
for /f "tokens=1-4 delims=." %%c in ("%%b") do (
set _o1=%%c
set _o2=%%d
set _o3=%%e
set _o4=%%f
rem strip leading space from first octet
set _4octet=!_o1:~1!.!_o2!.!_o3!.!_o4!
echo !_4octet!
)
)
)
endlocal
将要列表报告的所有接口的 IPv4 地址ipconfig
。