Sometimes, especially in corporate networks, you may find yourself in a situation where you receive multiple DHCP offers for different subnets from one or more DHCP servers. The worst case I experienced included different firewall rules depending on which DHCP subnet you were issued, making network connectivity like a lottery!
Unfortunately there is no way to tell the Windows DHCP Client to select specific DHCP offers in preference to others. You can add firewall filters but that only works if the DHCP offers are received from entirely different DHCP servers and does not work for everybody. So I wrote this script to check the current lease subnet and go into a release and renew loop until a DHCP lease on the desired subnet is achieved:
“Get Specific DHCP Subnet.cmd”
@echo off rem *** Parameters rem Could pass as arguments but we want to double-click this rem as an icon with fixed parameters for a known subnet. setlocal set AdapterName=Local Area Connection set RequiredSubnet=10.20.30. rem *** Get current lease information ipconfig /all >"%~dp0DHCP Lease.txt" rem *** Loop until correct subnet is provided... :loop type "DHCP Lease.txt" find /c "%RequiredSubnet%" "%~dp0DHCP Lease.txt" if %errorlevel% == 0 goto found echo *** Wrong subnet or no lease. echo *** Trying again to get lease on subnet "%RequiredSubnet%"... ipconfig /release "%AdapterName%" >NUL ipconfig /renew "%AdapterName%" >"%~dp0DHCP Lease.txt" goto loop: rem ** Exit successfully when found :found echo *** DHCP lease on subnet "%RequiredSubnet%" obtained! endlocal exit /b 0
To use this you need to know the name of the network adapter on your machine and the first part of the subnet you want (usually the first three parts of the 4 part dotted IP address, e.g. “1.2.3.” from “126.96.36.199”). You could leave this blank to release all network adapters, but that just causes a delay and could interrupt other valid connections on a machine with multiple network adapters. It’s best to give your adapters a name which is easy to remember, so go to the control panel, network and sharing center, adapter settings, select the adapter then hit F2 (or right click then choose “Rename”) then type a good name, e.g. “Company”.
Once you have set the parameters correctly in the script, you can just double-click it from Windows Explorer when you need it. Note the use of the “%~dp0” path prefixes and “” quotes throughout to ensure this script works from any location and with spaces in the path or connection name.
The script also creates a temporary file called “DHCP Lease.txt” in the same directory as the script, which is useful for reference too. You may want to alter this script in two ways. First some people may want to change the script so the parameters are passed as command line arguments (but then it doesn’t work so easily from the desktop) and delete the temporary file or store it in a different place like “%TEMP%”.