【WIN32】【C/C++】删除默认路由

该代码示例展示了如何使用Win32 API进行默认路由的删除和添加操作,并提供了一个查询系统当前路由状况的简单方法。通过GetIpForwardTable获取路由表信息,DeleteIpForwardEntry删除默认路由,CreateIpForwardEntry恢复默认路由。此外,还实现了保存和恢复默认路由设置的功能。

Win32 API 路由[查询|删除|添加]

1、删除和添加Demo

没啥技巧,有官方的demo,直接上代码

// GetIsDeleteDefaultRot.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <Shlwapi.h>
#include <atlstr.h>

#define WL_INI_SECDETECT_CONFIG                         _T("\\config\\SecDetectConfig.ini") 

#pragma comment(lib, "iphlpapi.lib")

std::wstring GetRunDir()
{
	std::wstring wsPath;
	TCHAR szModule[1024];
	memset(szModule, 0, sizeof(szModule));
	GetModuleFileName(NULL, szModule, sizeof(szModule) / sizeof(szModule[0]));
	PathRemoveFileSpec(szModule);
	wsPath = szModule;
	return wsPath;
}

CString SwitchStatusStr(int iSwitch)
{
	CString strSwitch;
	strSwitch.Format(_T("%d"), iSwitch);
	return strSwitch;
}

/*
* @fn           DeleteDefaultRout
* @brief        删除/恢复默认网关
* @param[in]    dwDeleteIpForwardEntry: 为`1`表示要恢复默认路由,为`0`表示删除默认路由
* @param[out]
* @return       BOOL:  视入参而定,如果默认路由状态与入参要求一致或者操作如参数要求一致,则返回TRUE;
					反之,则返回FALSE,即最终默认路由状态与参数要求一致
*
* @detail
* @author      yimingSQ
* @date        2021-08-27
*/
BOOL GetIsDeleteDefaultRout(DWORD bToDeleteorAdd = 2)
{
	BOOL bRet = FALSE;
	// Declare and initialize variables
	PMIB_IPFORWARDTABLE pIpForwardTable = NULL;
	PMIB_IPFORWARDROW pRow = NULL; // 默认网关,添加时使用
	DWORD dwSize = 0;
	BOOL bOrder = FALSE;
	DWORD dwStatus = 0;

	// 默认路由保存路径
	std::wstring wsFilePath = L"c:\\2\\1.ini";

	// Identify the required size of the buffer.
	dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, bOrder);
	if (dwStatus == ERROR_INSUFFICIENT_BUFFER)
	{
		// Allocate memory for the table.
		if (!(pIpForwardTable = (PMIB_IPFORWARDTABLE)malloc(dwSize)))
		{
			printf(("pipForwardTable Malloc failed. Out of memory.\n"));
			goto _END_;
		}
		// Retrieve the table.
		dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, bOrder);
	}

	if (dwStatus != ERROR_SUCCESS)
	{
		printf(("getIpForwardTable failed.\n"));
		if (pIpForwardTable)
		{
			free(pIpForwardTable);
		}
		goto _END_;
	}

	// Search for the required row in the table. The default gateway has a destination
	// of 0.0.0.0. Be aware the table continues to be searched, but only
	// one row is copied. This is to ensure that, if multiple gateways exist, all of them are deleted.
	for (int i = 0; i < pIpForwardTable->dwNumEntries; i++)
	{
		if (pIpForwardTable->table[i].dwForwardDest == 0)
		{
			// Delete the old default gateway entry.
			if (bToDeleteorAdd == 0)
			{
				printf("当前操作删除默认路由\n");
				if (!pRow) {
					// Allocate some memory to store the row in; this is easier than filling
					// in the row structure ourselves, and we can be sure we change only the
					// gateway address.
					pRow = (PMIB_IPFORWARDROW)malloc(sizeof(MIB_IPFORWARDROW));
					if (!pRow) {
						printf("Malloc failed. Out of memory.\n");
						exit(1);
					}
					// Copy the row
					memcpy(pRow, &(pIpForwardTable->table[i]),
						sizeof(MIB_IPFORWARDROW));
				}

				// 先保存默认路由相关信息
				printf("开始保存默认路由\n");
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardDest"), SwitchStatusStr(pRow->dwForwardDest), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMask"), SwitchStatusStr(pRow->dwForwardMask), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardPolicy"), SwitchStatusStr(pRow->dwForwardPolicy), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardNextHop"), SwitchStatusStr(pRow->dwForwardNextHop), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardIfIndex"), SwitchStatusStr(pRow->dwForwardIfIndex), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardType"), SwitchStatusStr(pRow->dwForwardType), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardProto"), SwitchStatusStr(pRow->dwForwardProto), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardAge"), SwitchStatusStr(pRow->dwForwardAge), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardNextHopAS"), SwitchStatusStr(pRow->dwForwardNextHopAS), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMetric1"), SwitchStatusStr(pRow->dwForwardMetric1), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMetric2"), SwitchStatusStr(pRow->dwForwardMetric2), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMetric3"), SwitchStatusStr(pRow->dwForwardMetric3), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMetric4"), SwitchStatusStr(pRow->dwForwardMetric4), wsFilePath.c_str());
				WritePrivateProfileString(_T("RECOVER"), _T("dwForwardMetric5"), SwitchStatusStr(pRow->dwForwardMetric5), wsFilePath.c_str());

				// 删除默认路由
				dwStatus = DeleteIpForwardEntry(&(pIpForwardTable->table[i]));
				if (dwStatus == NO_ERROR)
				{
					printf(("DeleteIpForwardEntry Success!"));
				}
				else
				{
					printf(("DeleteIpForwardEntry Error: %d\n"), dwStatus);
				}
				printf("删除结束\n");
			}

			bRet = TRUE;
			goto _END_;
		}
	}

	if (bToDeleteorAdd == 1) // 恢复默认路由
	{
		printf("要恢复默认路由\n");
		pRow = (PMIB_IPFORWARDROW)malloc(sizeof(MIB_IPFORWARDROW));

		pRow->dwForwardDest = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardDest"), -1, wsFilePath.c_str());
		pRow->dwForwardMask = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMask"), -1, wsFilePath.c_str());
		pRow->dwForwardPolicy = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardPolicy"), -1, wsFilePath.c_str());
		pRow->dwForwardNextHop = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardNextHop"), -1, wsFilePath.c_str());
		pRow->dwForwardIfIndex = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardIfIndex"), -1, wsFilePath.c_str());
		pRow->dwForwardType = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardType"), -1, wsFilePath.c_str());
		pRow->dwForwardProto = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardProto"), -1, wsFilePath.c_str());
		pRow->dwForwardAge = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardAge"), -1, wsFilePath.c_str());
		pRow->dwForwardNextHopAS = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardNextHopAS"), -1, wsFilePath.c_str());
		pRow->dwForwardMetric1 = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMetric1"), -1, wsFilePath.c_str());
		pRow->dwForwardMetric2 = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMetric2"), -1, wsFilePath.c_str());
		pRow->dwForwardMetric3 = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMetric3"), -1, wsFilePath.c_str());
		pRow->dwForwardMetric4 = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMetric4"), -1, wsFilePath.c_str());
		pRow->dwForwardMetric5 = GetPrivateProfileIntW(_T("RECOVER"), _T("dwForwardMetric5"), -1, wsFilePath.c_str());

		// Create a new route entry for the default gateway.
		dwStatus = CreateIpForwardEntry(pRow);
	}

_END_:
	if (pRow)
	{
		free(pRow);
	}
	// Free the memory. 
	if (pIpForwardTable)
	{
		free(pIpForwardTable);
	}
	return bRet;
}

BOOL SetIsDeleteDefaultRout(DWORD dwDeleteIpForwardEntry)
{
	BOOL bRet = FALSE;
	BOOL bDefaultIp = FALSE;

	if (dwDeleteIpForwardEntry == 1 || dwDeleteIpForwardEntry == 0 )
	{
		printf("开始执行,当前类型(%d)\n",dwDeleteIpForwardEntry);
	}
	else
	{
		printf(("SetIsDeleteDefaultRout wrong parameter(%d)\n"),dwDeleteIpForwardEntry);
		goto _END_;
	}

	bDefaultIp = GetIsDeleteDefaultRout();

	if (bDefaultIp == dwDeleteIpForwardEntry)
	{
		printf("当前主机状态已满足操作要求,程序结束!\n");
		bRet = TRUE;
		goto _END_;
	}
	else
	{
		// dwDeleteIpForwardEntry == 1 // 恢复默认路由
		// dwDeleteIpForwardEntry == 0 // 删除默认路由
		GetIsDeleteDefaultRout(dwDeleteIpForwardEntry);
	}

_END_:
	return bRet;
}

int main()
{
    std::cout << "请输入需要执行的操作(数字):\n0. 删除默认路由\n1. 恢复默认路由\n其他数字: 查询默认路由";
	DWORD dwIn;
	cin >> dwIn;
	SetIsDeleteDefaultRout(dwIn);
}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件

2、查询系统当前的路由情况

接口描述
GetIpForwardTable参考MSCN
// Need to link with Ws2_32.lib and Iphlpapi.lib
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <WS2tcpip.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996)

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

/* Note: could also use malloc() and free() */

int main()
{

	// Declare and initialize variables.

	/* variables used for GetIfForwardTable */
	PMIB_IPFORWARDTABLE pIpForwardTable;
	DWORD dwSize = 0;
	DWORD dwRetVal = 0;

	char szDestIp[128];
	char szMaskIp[128];
	char szGatewayIp[128];

	struct in_addr IpAddr;

	int i;

	pIpForwardTable =
		(MIB_IPFORWARDTABLE *)MALLOC(sizeof(MIB_IPFORWARDTABLE));
	if (pIpForwardTable == NULL) {
		printf("Error allocating memory\n");
		return 1;
	}

	if (GetIpForwardTable(pIpForwardTable, &dwSize, 0) ==
		ERROR_INSUFFICIENT_BUFFER) {
		FREE(pIpForwardTable);
		pIpForwardTable = (MIB_IPFORWARDTABLE *)MALLOC(dwSize);
		if (pIpForwardTable == NULL) {
			printf("Error allocating memory\n");
			return 1;
		}
	}

	/* Note that the IPv4 addresses returned in
	 * GetIpForwardTable entries are in network byte order
	 */
	if ((dwRetVal = GetIpForwardTable(pIpForwardTable, &dwSize, 0)) == NO_ERROR) {
		printf("\tNumber of entries: %d\n",
			(int)pIpForwardTable->dwNumEntries);
		printf("开始找默认路由\n");
		for (i = 0; i < (int)pIpForwardTable->dwNumEntries; i++) {
			/* Convert IPv4 addresses to strings */
			// 这里我加了判断,只打印默认路由,可以去掉
			if (pIpForwardTable->table[i].dwForwardDest == 0)
			{
				cout << "找到默认路由!!!!!!!!!\n" << endl;
			}
			else
			{
				continue;
			}
			IpAddr.S_un.S_addr =
				(u_long)pIpForwardTable->table[i].dwForwardDest;
			strcpy_s(szDestIp, sizeof(szDestIp), inet_ntoa(IpAddr));
			IpAddr.S_un.S_addr =
				(u_long)pIpForwardTable->table[i].dwForwardMask;
			strcpy_s(szMaskIp, sizeof(szMaskIp), inet_ntoa(IpAddr));
			IpAddr.S_un.S_addr =
				(u_long)pIpForwardTable->table[i].dwForwardNextHop;
			strcpy_s(szGatewayIp, sizeof(szGatewayIp), inet_ntoa(IpAddr));

			printf("\n\tRoute[%d] Dest IP: %s\n", i, szDestIp);		// 目标IP地址
			printf("\tRoute[%d] Subnet Mask: %s\n", i, szMaskIp);	// 子网掩码
			printf("\tRoute[%d] Next Hop: %s\n", i, szGatewayIp);	// 下一跳IP
			printf("\tRoute[%d] If Index: %ld\n", i,				// 
				pIpForwardTable->table[i].dwForwardIfIndex);
			printf("\tRoute[%d] Type: %ld - ", i,
				pIpForwardTable->table[i].dwForwardType);
 			switch (pIpForwardTable->table[i].dwForwardType) {
			case MIB_IPROUTE_TYPE_OTHER:
				printf("other\n");
				break;
			case MIB_IPROUTE_TYPE_INVALID:
				printf("invalid route\n");
				break;
			case MIB_IPROUTE_TYPE_DIRECT:
				printf("local route where next hop is final destination\n");
				break;
			case MIB_IPROUTE_TYPE_INDIRECT:
				printf
				("remote route where next hop is not final destination\n");
				break;
			default:
				printf("UNKNOWN Type value\n");
				break;
			}
			printf("\tRoute[%d] Proto: %ld - ", i,
				pIpForwardTable->table[i].dwForwardProto);
			switch (pIpForwardTable->table[i].dwForwardProto) {
			case MIB_IPPROTO_OTHER:
				printf("other\n");
				break;
			case MIB_IPPROTO_LOCAL:
				printf("local interface\n");
				break;
			case MIB_IPPROTO_NETMGMT:
				printf("static route set through network management \n");
				break;
			case MIB_IPPROTO_ICMP:
				printf("result of ICMP redirect\n");
				break;
			case MIB_IPPROTO_EGP:
				printf("Exterior Gateway Protocol (EGP)\n");
				break;
			case MIB_IPPROTO_GGP:
				printf("Gateway-to-Gateway Protocol (GGP)\n");
				break;
			case MIB_IPPROTO_HELLO:
				printf("Hello protocol\n");
				break;
			case MIB_IPPROTO_RIP:
				printf("Routing Information Protocol (RIP)\n");
				break;
			case MIB_IPPROTO_IS_IS:
				printf
				("Intermediate System-to-Intermediate System (IS-IS) protocol\n");
				break;
			case MIB_IPPROTO_ES_IS:
				printf("End System-to-Intermediate System (ES-IS) protocol\n");
				break;
			case MIB_IPPROTO_CISCO:
				printf("Cisco Interior Gateway Routing Protocol (IGRP)\n");
				break;
			case MIB_IPPROTO_BBN:
				printf("BBN Internet Gateway Protocol (IGP) using SPF\n");
				break;
			case MIB_IPPROTO_OSPF:
				printf("Open Shortest Path First (OSPF) protocol\n");
				break;
			case MIB_IPPROTO_BGP:
				printf("Border Gateway Protocol (BGP)\n");
				break;
			case MIB_IPPROTO_NT_AUTOSTATIC:
				printf("special Windows auto static route\n");
				break;
			case MIB_IPPROTO_NT_STATIC:
				printf("special Windows static route\n");
				break;
			case MIB_IPPROTO_NT_STATIC_NON_DOD:
				printf
				("special Windows static route not based on Internet standards\n");
				break;
			default:
				printf("UNKNOWN Proto value\n");
				break;
			}

			printf("\tRoute[%d] Age: %ld\n", i,
				pIpForwardTable->table[i].dwForwardAge);
			printf("\tRoute[%d] Metric1: %ld\n", i,
				pIpForwardTable->table[i].dwForwardMetric1);
		}
		FREE(pIpForwardTable);
		return 0;
	}
	else {
		printf("\tGetIpForwardTable failed.\n");
		FREE(pIpForwardTable);
		return 1;
	}

}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欧恩意

如有帮助,感谢打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值