fosfik
fosfik

Reputation: 83

Echo is off (batch script)

This is my script (it put out ip from ipconfig)

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-2 delims=:" %%A in ('ipconfig^|find "IP"^|find ":10."') do set ip==%%B
set "ipaddress=%ip:~1%"
set "ipk=%ipaddress:~1,-2%"
echo %ipk%

What I get is: Echo is off

Upvotes: 1

Views: 756

Answers (2)

sst
sst

Reputation: 1463

You can't be sure that the last part of the ip address is a 2 digits number, It can be anything from 1 to 254, so cutting the the last 2 chars may not give you the right result.

Fortunately for this case, because the ip addresses are separated by . they can treated like file name extensions by the FOR modifiers.

And by using findstr (with regex search terms) instead of find for searching the ip address you can reduce the number of pipes from 2 to 1.

@echo off
set "ipk=IP_NOT_FOUND"
for /f "tokens=2 delims=:" %%A in ('ipconfig^|findstr /IRC:"IPv4.*: *10\."') do set "ipk=%%~nA."
set "ipk=%ipk: =%"
echo %ipk%
pause

However it is not clear what exactly ipk is representing, If you meant to display the network address, then this will most probably the wrong way to do it, because the network address depends of the value of the subnet mask which must be obtained separately and performing calculations with both the ipaddress and subnet mask to obtain the correct network address.

But this is out of scope of your question so I leave it as is.

And You should be aware that if there is more than one network adapter with 10. ip address then this will return the ip address of the last enumerated adapter.

Interpretation of the findstr regex term: "IPv4.*: *10\."
IPv4 A line which contains the string "IPv4" (case insensitive because the /I switch)
.*: followed by zero or more of any character, followed by a colon :
*10\. followed by zero or more spaces, followed by 10. and the rest of the line if any.

Upvotes: 2

user7818749
user7818749

Reputation:

Your network range might eventually expand to other IP ranges so I thought I would add another option where you would not have to hard code your starting range. So this is more of an extension to your query.

Here I just take the subnet configured, get the IP in that range and match to your IP, then echo it. It does not require you to hard code the IP's beginning range:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=2,3 delims={,}" %%a in ('"wmic nicconfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do set gate_test=%%~a
set gate_test=!gate_test: =!
for /f "tokens=1-2 delims=^." %%i in ("!gate_test!") do set range=%%i.%%j
    for /f "delims=:" %%l in ('ipconfig ^| findstr IPv4') do (
      set ip=%%m
      set ip=!ip: =!
      for /f "tokens=1-2 delims=^." %%n in ("!ip!") do set iprange=%%n.%%o
     if !iprange! == !range! set ipaddress=!ip!
   )
)
echo !ipaddress!

Upvotes: 0

Related Questions