根据IP地址与网关的对应关系:必须在同一网段
我这里粗暴的理解为IP地址与网关的第一段数字是相同的,如果不对,欢迎给出正确解释
根据以上的观点,我参考了其他贴的范例,写了下面这个批处理可以达到我的要求
本人水平有限,欢迎高手修改和精简
- @echo off & setlocal enabledelayedexpansion
- :kaishi
- cls
- set IP=
- set GW=
- set GW0=
- echo 请选择一个网卡:
- set "choice="
- set "count=1"
- for /f "tokens=1 delims=:" %%a in ('netsh interface ipv4 show addresses ^| findstr "接口"') do (
- set "adapter=%%a"
- set "adapter=!adapter:~4,-5!"
- echo !count!. !adapter!
- set "interface!count!=!adapter!"
- set /a "count+=1"
- )
- set /p "choice=请输入序号:"
- set "interfaceName=!interface%choice%!"
- for /f "tokens=1-2 delims=:" %%i in ('netsh interface ipv4 show config name^="!interfaceName!" ^| findstr /C:"IP 地址"') do (
- set "ip_line=%%j"
- for /f "tokens=*" %%f in ("!ip_line!") do set "IP=%%f")
- if not "!IP!"=="" (echo !interfaceName! 的IP地址:!IP! ) ELSE echo !interfaceName! 没有配置IP地址 无法查到对应的默认网关&pause>nul 2>nul &goto :kaishi
- for /f "tokens=1-2 delims=:" %%i in ('netsh interface ipv4 show config name^="!interfaceName!" ^| findstr /C:"默认网关"') do (
- set "gateway=%%j"
- for /f "tokens=*" %%f in ("!gateway!") do set "GW=%%f")
- )
- if not "!GW!"=="" echo !interfaceName! 的默认网关:!GW! &pause>nul 2>nul &goto :kaishi
- for /f "tokens=1 delims=." %%a in ("!IP!") do set "ip1=%%a" & rem 提取IP地址第一段作为变量
- for /F "tokens=3" %%i in ('route print -4 ^| findstr /C:" "') do echo %%i>>%temp%\ip0.txt & rem 导出路由网关列并保存在临时文件中
- for /f %%f in ('findstr "!ip1!" %temp%\ip0.txt') do set GW0=%%f & rem 查找IP地址第一段与路由网关列中最后一个匹配值
- if "!GW0!"=="" echo !interfaceName! 没有找到与IP地址对应的网关配置 &del /q %temp%\ip0.txt>nul 2>nul&pause>nul 2>nul &goto :kaishi
- echo !interfaceName! 的默认网关:!GW0! &del /q %temp%\ip0.txt>nul 2>nul&pause>nul 2>nul &goto :kaishi
复制代码
|