简体   繁体   中英

How to convert IP address to integer using batch file

I have 2 problem statements

1:

I need to read read an IP address from a text file and increment the value by 1 and store it in a variable. This all I have to do using a batch script.

This is how my text file looks like -

MyIpAddressList.txt
192.168.1.105

I am able to read it as string and store & print it

for /f "delims=" %%x in (IPADDRESSLIST.txt) do set /p IPAddress=%%x+1
ECHO %IPAddress%

But when I am trying to read it as number as mentioned set /a IPAddress=%%x+1" it does't work.

2:

I have to run a loop for 100 times and pass this IP address as an input to another batch script and increament this ip address by 1. Example:

Main_Batch_File.bat

READ MyIpAddressList.txt and store IP address in IPAddress
IPAddress = 192.168.1.105
LOOP 100 times
CALL Another_Batch_Script(IPAddress)
IPAddress++
LOOP END

I am not sure if it is possible using a batch file and apologise if this does not make sense.

setlocal enabledelayedexpansion
for /f "tokens=1,2,3,4 delims=." %%a in (%ipaddress%) do (
  set/a suffix=1%%d-1000
  for /l %%i in (1,1,100) do (
    set/a suffix+=1
    call "yourscript.bat" %%a.%%b.%%c.!suffix! 
  )

first we split ipaddress in four tokens. then handle the fourth. the set/a suffix=1%%d-1000 avoids numbers below 100 (ie 080) being treated as octal

EDIT: as TripeHound suggested, if you need to start from current address, move the increment behind the call statement.

elzoologico's solution expanded to avoid the "overflow" problem, TripeHound mentioned:

@echo off
set ipaddress=192.168.001.015
setlocal enabledelayedexpansion
for /f "tokens=1-4 delims=." %%a in ("%ipaddress%") do (
  set /a suffix=1%%d-1000
  set /a final=suffix+100
  if !final! gtr 255 set final=255
  for /l %%i in (!suffix!,1,!final!) do (
    ECHO call "yourscript.bat" %%a.%%b.%%c.%%i 
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM