SoFunction
Updated on 2025-03-10

BAT batch determines the IP address and automatically disables the enable network card

A problem with the design of an intranet dialing software. After dialing, DHCP cannot be automatically obtained by chance to update the intranet IP. Later, I found that manually releasing and reacquisition of IP can be solved. However, before each operation, you have to check whether the IP address has been updated to the intranet address. If it has been updated, there is no need to operate, otherwise you have to manually release the update. It is really troublesome to type a bunch of commands every time, so you plan to do it in batch processing.

The first problem we encountered is how to obtain the IP address. Of course, since batch processing is adopted, it is necessary to use existing commands or command line programs. The IPconfig command in the Windows system can obtain IP address and other information. If we only need the IP address, we must filter the obtained information, which requires the cooperation of findstr and other tools. Combined with the examples found on the Internet, the final code is as follows:

Copy the codeThe code is as follows:

for /f "tokens=2 delims=:" %%i in ('ipconfig^|findstr "Address"') do set ip=%%i
SET ip=%ip:~1%

In this way, the IP address is saved in the ip variable, and we can obtain it through ECHO %ip%. Then we need to determine whether this IP address is an intranet sub-segment. Here we are simple. It is known that the intranet is all 10. The header IP address, while other IP segments are removed from any IP segments that are 10. The header IP segments are then removed. Then the problem is simple. Just intercept the first 3 digits of the IP address and determine whether it is 10. It's done. I will post the complete code here for your reference. It is relatively simple to write:

Copy the codeThe code is as follows:

@ECHO OFF
for /f "tokens=2 delims=:" %%i in ('ipconfig^|findstr "Address"') do set ip=%%i
SET ip=%ip:~1%
set id=%ip:~0,3%
ECHO Current IP Address : %ip%
if NOT "%id%"=="10." goto FIXIPADDR
ECHO It seems OK:-)
goto END

:FIXIPADDR
ECHO Fix DHCP Configuration
ECHO Please wait...
ipconfig /release>NUL 1>NUL 2>NUL
ipconfig /renew>NUL 1>NUL 2>NUL

ECHO All Done
:END
PAUSE