当前日期:2023年06月05日 星期一
Hi 你好,欢迎访问!登录
搜索 导航

凯特网-Think and Do it , as Soon as!

当前位置:首页 - 程序设计 - C++ - 正文
阅读模式

根据IP及子网掩码计算网关

2021-09-02 | C++ | caterwang | 9429°c

linux网络配置中,经常只知道IP和子网掩码,但是又需要配置网关。以下是网上薅(hao平声)来的代码,又根据自己的需要做的修改。有需要同学注意选择使用。

//根据IP及子网掩码计算网关
bool CalGateWay(const unsigned char *ip,const unsigned char *mask, unsigned char *gw,int datlen)
{
	unsigned char ip_s[20],mask_s[20];
	unsigned char ip_d[4],mask_d[4],gw_d[4];
	char* tmp = NULL;
	int index;
	//以下操作会影响ip及mask的值,所以需要备份一份出来用
	memcpy(ip_s,ip,datlen);
	memcpy(mask_s,mask,datlen);
	
	tmp = strtok ((char *)ip_s, ".");	
	index = 0;
	while(tmp!=NULL)
	{
		ip_d[index]=atoi(tmp);
		tmp = strtok (NULL, ".");
		index++;
	}
	
	tmp = strtok ((char *)mask_s, ".");
	index = 0;
	while(tmp!=NULL)
	{
		mask_d[index]=atoi(tmp);
		tmp = strtok (NULL, ".");
		index++;
	}
	
	for(index=0;index < 4;index++)
	{
		gw_d[index]=(ip_d[index] & mask_d[index]);
	}
	
	gw_d[3] += 1;

	snprintf((char*)gw,datlen,"%d.%d.%d.%d",gw_d[0],gw_d[1],gw_d[2],gw_d[3]);

	return true;
}


请使用支付宝赞助我

支付宝打赏

请使用微信赞助我

微信打赏

版权声明

欢迎转载,但注明出处,谢谢!

分享:
0
QR:  根据IP及子网掩码计算网关

扫一扫,用手机打开吧

推荐文章

共0条评论

暂时没有评论,你可以来抢个沙发!

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

展开