windows下用C++修改本机IP地址

时间:2024-01-11 08:15:32

两种方法

第一种、使用DOS命令(即时生效)

  windows下用C++修改本机IP地址

第二种、修改注册表(重启生效)

1、打开SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards

  RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards",0,KEY_READ,&hKey)

2、取出打开注册表下的所有子键

  RegEnumKeyEx(hKey,dwIndex++,szSubKey,&dwBufSize,NULL,NULL,NULL,NULL)

3、打开子键

  RegOpenKeyEx(hKey,szSubKey,0,KEY_READ,&hSubKey)

4、得到网卡的ServiceName

  RegQueryValueEx(hSubKey,"ServiceName",0,&dwDataType,szData,&dwBufSize)

5、根据网卡ServiceName打开新注册表

  RegOpenKeyEx(HKEY_LOCAL_MACHINE,“SYSTEM\\CurrentControlSet\\services\\”+szData+"\\Parameters\\Tcpip",0,KEY_ALL_ACCESS,&hLocalKey)

6、修改本机网络信息

  //IP

  RegSetValueEx(hLocalKey,"IPAddress",0,type_ip,"192.168.123.123",dwIPSize)

  //SubnetMask

  RegSetValueEx(hLocalKey,"SubnetMask",0,type_SubnetMask,"255.255.255.0",dwSubnetMaskSize)

  //GateWay

  RegSetValueEx(hLocalKey,"DefaultGateway",0,type_GateWay,"192.168.12.1",dwGateWaySize)

windows下用C++修改本机IP地址