WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

How To
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Change Ip Address


TCP/IP parameters in the registry are well documented. What's a little bit more tricky is finding the network card entry in the registry. Let's look at it step by step:

  1. Enumerate the subkeys in:
        HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\NetworkCards
    

    Each subkey represents a network card in the machine (including virtual network cards, such as dial up adapters). In this subkey we can find useful information about the network card, such as its name, description, driver or manufacturer. The entry we are looking for is ServiceName. It indicates the name of the service associated to this network card in the service database.

  2. Each network card configuration parameters are in:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\{ServiceName}\Parameters\
    

    If the network card is bound to TCP/IP, TCP/IP parameters for this card are under subkey TcpIP. TCP/IP parameters are well documented in MSDN. If you just want to change the IP address, we should look at:

        IPAddress: REG_MULTI_SZ: This is the list of IP Addresses for this
    adapter. Notice that DHCPEnabled must be set to FALSE for these addresses to
    be used.
        DHCPEnabled: REG_DWORD: This is wether this adapter uses DHCP to get
    configuration information or not. If we are setting the IP Address, we must
    set this to FALSE (0).
    
; Right way to change the IP address of an adapter. 
; The disadvantage is that you have to reboot your machine.
ipaddr = AskLine ("Ip Address Changer", "Enter the new IP address", "172.16.")

keypath = "Software\Microsoft\Windows NT\CurrentVersion\NetworkCards"
key=RegOpenkey(@RegMachine, keypath)
keylist = RegQueryKeys(key)
keycount = ItemCount(keylist,@tab)

for xx = 1 to keycount
   subkey = ItemExtract(xx,keylist,@tab)
	subkeypath = StrCat(keypath,"\",subkey,"[ServiceName]")
	if RegExistValue(@RegMachine,subkeypath)
		servicename=RegQueryValue(@regmachine,subkeypath)
		subkey = StrCat("SYSTEM\CurrentControlSet\Services\",ServiceName,"\Parameters\TcpIp") 
		if RegExistKey(@regmachine,subkey)
		    ;RegSetDword(@regmachine,StrCat(subkey,"[DHCPEnabled]"),0);DHCPEnabled must be set to FALSE for these addresses to be used.
			 ;RegSetMulSz(@regmachine,StrCat(subkey,"[IpAddress]"),ipaddr," ")			 
		endif
	endif
next
The above is the right way to change the IP address of an adapter. The disadvantage is that you have to reboot your machine. TCP/IP reads these parameters every time it binds to an adapter (usually, at system startup). The only way to make IP to read those parameters again is forcing it to unbind from the adapter and bind to it again. It happens when you unload the network card driver and load it again. Unfortunately, not all the network card adapter drivers can unload and load themselves (only NDIS 4.0 drivers can and, usually, only PCMCIA drivers do). You can try stopping your device driver and trying to start it again from Control Panel\Devices. It doesn't work for the network cards in my computer.

The change of IP address of an adpater is not a trivial operation, anyway. You can lose data, because you force all the sockets to close, all the services to restart on that adapter, the route table must be updated, etc., etc.


Using NetSh.exe (no reboot required)

Apparently you can usethe utility NetSh.exe to change the IP address without rebooting According to the Microsoft KB article Q257748, "How to Use the NETSH Command to Change from Static IP Address to DHCP in Windows 2000," NetSh.exe (NetShell) can be used to change the IP address of a network interface without restarting the computer. Also, reversely, it can be used to set the interface to use DHCP. But remember to run afterward "IPConfig /renew" to request an IP address from a DHCP server.

To programmatically launch NetSh.exe with a command line, you can use the Run function.


Using WMI

Use WMI's Win32_NetworkAdapterConfiguration class to find the adapter(s) and set the static IP address with the EnableStatic() method. WMI is part of the Windows 2000 and Millennium operating systems.

I found a sample at http://cwashington.netreach.net/depo/view.asp?Index=628&ScriptType=vbscript. Though it is VBScript, you may get hints from it.

WMI:

Win32_NetworkAdapterConfiguration:

http://msdn.microsoft.com/library/en-us/wmisdk/r_32hard4_6oq6.asp

Methods: EnableStatic + EnableDHCP

http://msdn.microsoft.com/library/en-us/wmisdk/r_32hard4_0ujy.asp

http://msdn.microsoft.com/library/en-us/wmisdk/r_32hard4_27u6.asp

Change ip VB-Scripts:

http://desktopengineer.com/index.php?topic=0080WMI

http://cwashington.netreach.net/depo/view.asp?Index=628

VERY simplified WMI sample:
// ===============================================================================
using System;
using System.Management;
using System.Threading;

namespace WmiIpChanger
{
class IpChanger
{
[MTAThread]
static void Main(string[] args)
{
ReportIP();
// SwitchToDHCP();
SwitchToStatic();
Thread.Sleep( 5000 );
ReportIP();
Console.WriteLine( "end." );
}

static void SwitchToDHCP()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue;

inPar = mo.GetMethodParameters("EnableDHCP");
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
}

static void SwitchToStatic()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;

inPar = mo.GetMethodParameters( "EnableStatic" );
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
break;
}
}

static void ReportIP()
{
Console.WriteLine( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;

Console.WriteLine( "{0}\n SVC: '{1}' MAC: [{2}]", (string) mo["Caption"],
(string) mo["ServiceName"], (string) mo["MACAddress"] );

string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];

Console.WriteLine( " Addresses :" );
foreach(string sad in addresses)
Console.WriteLine( "\t'{0}'", sad );

Console.WriteLine( " Subnets :" );
foreach(string sub in subnets )
Console.WriteLine( "\t'{0}'", sub );
}
}
}
}

// ===============================================================================
WARNING: do MUCH more error checking, multiple NIC tests, timing!... use all at at your own risk!

If you like, low-level IP-Helper API:

http://msdn.microsoft.com/library/en-us/tcpip/iphpport_7vz9.asp

PInvoke with C# (no IP change impl.?)

http://www.gotdotnet.com/team/p2p/

http://www.gotdotnet.com/userfiles/herveyw/netsamples.zip


Environment: NT4 SP5

How to set local machine IP addresses from your program ?

Follow this steps

  1. Open registry on the HKEY_LOCAL_MACHINE

  2. Find the subKey = SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\netcard# netcard# usually is "1" but you can control any subkey and find specific netwrok Adapters Refer to "MSDN Registry Entries for Network Adapter Cards"

  3. Get data for the value "ServiceName"

  4. Find the subKey = SYSTEM\CurrentControlSet\Services\"ServiceName"\Parameters\TcpIp"

  5. Set data for the value "IpAddress" to change IP address

  6. Set data for the value "SubnetMask" to change subnet mask

  7. Set data for the value "DefaultGateway" to change default gateway

  8. Reboot your PC.

How to set local machine HostName from your program ? Follow this steps:

  1. Open registry on the HKEY_LOCAL_MACHINE

  2. Find the subKey = SYSTEM\CurrentControlSet\Services\TcpIp\Parameters

  3. Set data for the value "HostName"

  4. Find the subKey = SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName

  5. Set data for the value "ComputerName"

  6. Reboot your PC and HostName will be set.
WARNING: Modify registry incorrect can cause serious, system-wide problems . Use this at your own risk

ipaddr =  ""
subnet = ""
gateway = ""

keypath = "Software\Microsoft\Windows NT\CurrentVersion\NetworkCards"
key=RegOpenkey(@RegMachine, keypath)
keylist = RegQueryKeys(key)
keycount = ItemCount(keylist,@tab)

for xx = 1 to keycount
	subkey = 
	if RegExistValue(@regmachine,key)
		servicename=RegQueryValue(@regmachine,key)
		subkey = StrCat("SYSTEM\CurrentControlSet\Services\",ServiceName,"\Parameters\TcpIp") 
		if RegExistKey(@regmachine,subkey)
			 ;RegSetValue(@regmachine,StrCat(subkey,"[IpAddress]"),ipaddr)
			 ;RegSetValue(@regmachine,StrCat(subkey,"[SubnetMask]"),subnet)
			 ;RegSetValue(@regmachine,StrCat(subkey,"[DefaultGateway]"),gateway)
		endif
	endif
next



Article ID:   W15957
File Created: 2004:03:30:15:42:04
Last Updated: 2004:03:30:15:42:04