根据IP及子网掩码计算网关
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; }
凯特网版权声明:以上内容允许转载,但请注明出处,谢谢!