Hack 43 Change from Static IP to DHCP

figs/moderate.gif figs/hack43.gif

Reconfiguring a network from static IP addressing to DHCP is a chore no system administrator wants to do, but now there's help.

Companies grow over time, and their networks have to grow along with them. This means that the static IP addressing that was used when the network was small will no longer practical once the systems number more than a few dozen. Unfortunately, changing machines from static to dynamic addressing usually means visiting each machine, logging on as a local administrator, and clicking through numerous properties sheets to reconfigure TCP/IP settings for network adapters.

However, there's an easier way. The VBScript in this hack uses Registry writes to change the TCP/IP settings on a machine from static IP to DHCP.

The Code

Type the script into Notepad (with Word Wrap disabled) and save it with a .vbs extension as Static2DHCP.vbs:

'All variables declared

Option Explicit

Dim oWSHShell

Dim sNIC, sMan

Dim iCount

Set oWSHShell = WScript.CreateObject("WScript.Shell")

' Set the DCHP service to autostart

oWSHShell.RegWrite "HKLM\SYSTEM\CurrentControlSet\Services\DHCP\Start", 2

' Get Network card

On Error Resume Next

iCount = 1


sNIC = oWSHShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\ " & _

"CurrentVersion\NetworkCards\" & iCount & "\ServiceName")

sMan = oWSHShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\ " & _

"CurrentVersion\NetworkCards\" & iCount & "\Manufacturer")

' Skip the Async and NDIS services

If sMan <> "Microsoft" And Err.Number = 0 Then

Call SetNIC

End If

iCount = iCount + 1

Loop Until Err.Number <> 0

' Clear the error


' End of Script

Sub SetNIC

Dim iTest

' Set the NIC service to use DHCP

sNIC = "HKLM\SYSTEM\CurrentControlSet\Services\" & sNIC &"\Parameters\TCPIP\"

iTest = oWSHShell.RegRead(sNIC & "EnableDHCP")

If iTest = 0 Then

oWSHShell.RegWrite sNIC & "EnableDHCP", 1, "REG_DWORD"

oWSHShell.RegWrite sNIC & "IPAddress", "", "REG_MULTI_SZ"

oWSHShell.RegWrite sNIC & "SubnetMask", "", "REG_MULTI_SZ"

End If

End Sub

Running the Hack

To run this hack, call the Static2DHCP.vbs script from a logon script and use Group Policy to assign this logon script to users' machines. When a user next logs on to his machine, the machine's TCP/IP settings will be changed from static to dynamic addressing. To lease an address from the DHCP server, the user's machine needs to be rebooted, so you could also send out a message asking all users to reboot their machines using the method in [Hack #35] or some other approach. If you like, the logon script could also be combined with the SU utility from the Windows 2000 Server Resource Kit to perform a hands-off migration from static to dynamic addressing.

?Rod Trent