Windows CE: Changing Static IP Address
- by Bruce Eitman
A customer contacted me recently and asked me how to change a static IP address at runtime. Of course this is not something that I know how to do, but with a little bit of research I figure out how to do it.
It turns out that the challenge is to request that the adapter update itself with the new IP Address. Otherwise, the change in IP address is a matter of changing the address in the registry for the adapter. The registry entry is something like:
[HKEY_LOCAL_MACHINE\Comm\LAN90001\Parms\TcpIp] "EnableDHCP"=dword:0 "IpAddress"="192.168.0.100" "DefaultGateway"="192.168.0.1" "Subnetmask"="255.255.255.0"
Where LAN90001 would be replace with your adapter name. I have written quite a few articles about how to modify the registry, including a registry editor that you could use.
Requesting that the adapter update itself is a matter of getting a handle to the NDIS driver, and then asking it to refresh the adapter. The code is:
#include <windows.h>
#include "winioctl.h"
#include "ntddndis.h"
void RebindAdapter( TCHAR *adaptername )
{
HANDLE hNdis;
BOOL fResult = FALSE;
int count;
// Make this function easier to use - hide the need to have two null characters.
int length = wcslen(adaptername);
int AdapterSize = (length + 2) * sizeof( TCHAR );
TCHAR *Adapter = malloc(AdapterSize);
wcscpy( Adapter, adaptername );
Adapter[ length ] = '\0';
Adapter[ length +1 ] = '\0';
hNdis = CreateFile(DD_NDIS_DEVICE_NAME,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
0,
NULL);
if (INVALID_HANDLE_VALUE != hNdis)
{
fResult = DeviceIoControl(hNdis,
IOCTL_NDIS_REBIND_ADAPTER,
Adapter,
AdapterSize,
NULL,
0,
&count,
NULL);
if( !fResult )
{
RETAILMSG( 1, (TEXT("DeviceIoControl failed %d\n"), GetLastError() ));
}
CloseHandle(hNdis);
}
else
{
RETAILMSG( 1, (TEXT("Failed to open NDIS Handle\n")));
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
RebindAdapter( TEXT("LAN90001") );
return 0;
}
If you don’t want to write any code, but instead plan to use a registry editor to change the IP Address, then there is a command line utility to do the same thing. NDISConfig.exe can be used:
Ndisconfig adapter rebind LAN90001
Copyright © 2012 – Bruce Eitman
All Rights Reserved