How to split an ip address into seperate octets and perform arithmetic in cmd

我们两清 提交于 2019-12-08 06:48:00

问题


What I am trying to do is configure some vlan scopes via cmd. What I have accomplished so far is to retrieve the IP Address of the Domain Controller and remove the space in front of the value. I have accomplished this using the following commands:

rem extract ip address via local cmd for /f "tokens=2 delims=:" %i in ('ipconfig ^| find /i "IPv4 Address"') do set ip_address=%i

example result: set ip_address= 10.0.0.25

rem remove empty space from ip address var set ip_address=%ip_address: =%

echo %ip_address% now results in 10.0.0.25 without the space in front.

What I would like to do next is split the ip_address variable in separate octet variables so that arithmetic can be performed on the octet of choice.

For example: 10.0.0.25 could then be manipulated to reflect 10.[+100].0.[-24]

the desired result would then be 10.100.0.1

I would prefer to accomplish this strictly using windows command line but if a better method exits I am open to suggestions.

Thanks in advance Joel


回答1:


Try this to split up the octets into variables.

@echo off
set "ip=10.0.0.25"
SET "offsets=0.100.0.-24"

@echo off
for /f "tokens=1-4 delims=. " %%a in ("%ip%") do (
set octetA=%%a
set octetB=%%b
set octetC=%%c
set octetD=%%d
)
FOR /f "tokens=1-4 delims=." %%a in ("%offsets%") do (
SET /a octetA+=%%a
SET /a octetB+=%%b
SET /a octetC+=%%c
SET /a octetD+=%%d
)
echo "%octetA%","%octetB%","%octetC%","%octetD%"
pause



回答2:


This is the same solution of foxidrive, but squashed a little... :)

@echo off
set "ip= 10.0.0.25"
SET "offsets=0.100.0.-24"

for /F "tokens=1-4 delims=. " %%a in ("%ip%") do (
   for /F "tokens=1-4 delims=." %%i in ("%offsets%") do (
      set /A octetA=%%a+%%i, octetB=%%b+%%j, octetC=%%c+%%k, octetD=%%d+%%l
   )
)
echo "%octetA%","%octetB%","%octetC%","%octetD%"
pause



回答3:


Are you aware of autohotkey?

Also, you could try a powershell script.



来源:https://stackoverflow.com/questions/16847871/how-to-split-an-ip-address-into-seperate-octets-and-perform-arithmetic-in-cmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!