#include <ndis.h>
bool SetIpAddress(CString m_strIp,CString m_strMask,CString m_strGateWay)
{
//获得网卡的设备名
WCHAR Names[50];
DWORD bytes;
HANDLE m_hFileHandle = CreateFile(_T("NDS0:"), 0, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
(HANDLE) INVALID_HANDLE_VALUE);
if( m_hFileHandle == INVALID_HANDLE_VALUE )
{
MessageBox(NULL,_T("获得网卡名时打开设备错误"),NULL,0);
return false;
}
// Get list of adapter names
if (!DeviceIoControl(m_hFileHandle,
IOCTL_NDIS_GET_ADAPTER_NAMES,
NULL,0,
Names,MAX_PATH,&bytes,NULL))
{
MessageBox(NULL,_T("获得网卡名错误"),NULL,0);
return false;
}
DWORD len = wcslen(Names);
Names[len] = 0;
Names[len+1] = 0;
CString strKeyName;
strKeyName.Format(_T("Comm\%s\Parms\TCPIP"),Names);
//打开注册表对网卡IP信息对应子健进行修改
HKEY hkey;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,strKeyName,0,KEY_WRITE,&hkey) != ERROR_SUCCESS)
{
MessageBox(NULL,TEXT("打开注册表错误"),NULL,0);
return false;
}
DWORD value;
value = 0;
WCHAR buffer[50];
//set EnableDHCP
if(RegSetValueEx(hkey,TEXT("EnableDHCP"),0,REG_DWORD,(const unsigned char *)&value,sizeof(DWORD)) != ERROR_SUCCESS)
MessageBox(NULL,TEXT("关闭自动获得IP错误"),NULL,0);
//set ip address
memset(buffer,0,100);
memcpy(buffer,m_strIp.GetBuffer(0),m_strIp.GetLength()*2);
if(RegSetValueEx(hkey,TEXT("IpAddress"),0,REG_MULTI_SZ,(const unsigned char *)buffer, m_strIp.GetLength()*2+2) != ERROR_SUCCESS)
MessageBox(NULL,TEXT("设置IP错误"),NULL,0);
//set subnet mask
memset(buffer,0,100);
memcpy(buffer,m_strMask.GetBuffer(0),m_strMask.GetLength()*2);
if(RegSetValueEx(hkey,TEXT("SubnetMask"),0,REG_MULTI_SZ,(const unsigned char *)buffer, m_strMask.GetLength()*2+2) != ERROR_SUCCESS)
MessageBox(NULL,TEXT("设置子网掩码错误"),NULL,0);
//set gateway
memset(buffer,0,100);
memcpy(buffer,m_strGateWay.GetBuffer(0),m_strGateWay.GetLength()*2);
if(RegSetValueEx(hkey,TEXT("DefaultGateway"),0,REG_MULTI_SZ,(const unsigned char *)buffer, m_strGateWay.GetLength()*2+2) != ERROR_SUCCESS)
MessageBox(NULL,TEXT("设置网关错误"),NULL,0);
RegFlushKey(hkey);
RegCloseKey(hkey);
// 重启网卡,不用机器热启动
HANDLE hNdis = CreateFile(_T("NDS0:"), 0, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
(HANDLE) INVALID_HANDLE_VALUE);
if( hNdis == INVALID_HANDLE_VALUE )
{
MessageBox(NULL,_T( "重启网络驱动时打开设备错误"),NULL,0);
return false;
}
// Send the device command.
if (!DeviceIoControl( hNdis, IOCTL_NDIS_REBIND_ADAPTER,
Names, _tcslen( Names) + sizeof( TCHAR ), // buf contains the name of the
NULL, 0, NULL, NULL ) )
{
MessageBox(NULL,_T( "重启网络驱动错误"),NULL,0);
}
CloseHandle( hNdis );
return true;
}
需注意:1 使
用标准SDK的朋友,可能用到的头文件有:pkfuncs.h,toolhelp.h,lss.h,自己需要到你的WINCE500目录下搜索这几个头文件;2 你的WINCE工程目录输出若不是debug版,上面头文件可能使用有错误,使用Release版将上面函数封装成一个静态库使用。
发表评论 取消回复