C++获取网关(linux)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zyx4843/article/details/53008955

这里只讨论最简单与直接的方法,和route命令一样,从/proc/net/route读取,代码如下:

bool GetIPV4Gateway(const char * pNICName, char *pGateway, unsigned long len)
{
	char buffer[200] = { 0 };
	unsigned long bufLen = sizeof(buffer);

	unsigned long defaultRoutePara[4] = { 0 };
	FILE * pfd = fopen(PATH_ROUTE, "r");
	if (NULL == pfd)
	{
		return false;
	}

	while (fgets(buffer, bufLen, pfd))
	{
		sscanf(buffer, "%*s %x %x %x %*x %*x %*x %x %*x %*x %*x\n", (unsigned int *)&defaultRoutePara[1], (unsigned int *)&defaultRoutePara[0], (unsigned int *)&defaultRoutePara[3], (unsigned int *)&defaultRoutePara[2]);

		if (NULL != strstr(buffer, pNICName))
		{
			//如果FLAG标志中有 RTF_GATEWAY
			if (defaultRoutePara[3] & RTF_GATEWAY)
			{
				unsigned long ip = defaultRoutePara[0];
				snprintf(pGateway, len, "%d.%d.%d.%d", (ip & 0xff), (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff);
				break;
			}
		}

		memset(buffer, 0, bufLen);
	}

	fclose(pfd);
	pfd = NULL;
	return true;
}

这里PATH_ROUTE是/proc/net/route

RTF_GATEWAY需要包括头文件#include <net/route.h>

假设要获取wifi的网关,比如wlan0

char gateway[32] = { 0 };
GetIPV4Gateway("wlan0", gateway, 32);



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页