发布网友 发布时间:2022-04-20 07:13
共1个回答
热心网友 时间:2023-09-07 01:58
#include <stdio.h>
#include <assert.h>
void take_num(const char *strIn, int *n, unsigned int *outArray)
{
const char * p = strIn;
int next = 0;
*n = 0;
outArray[0] = 0;
assert(p && n && outArray);
for (p = strIn;*p;p++) {
if (('0'<=*p)&&(*p<='9')) {
outArray[*n] = (outArray[*n] * 10)+((*p) - '0');
next = 1;/*后面还有*/
} else {
if (next == 1) {
(*n)++;
}
next = 0;
}
}
}
void max_prefix_match(const char *ip_addr, const char *net_addr_array[], int *n)
{
int ip,tar_net,tar_mask;/*ip地址*/
int ip_it[4],net_it[4],mask_it[4];
char * p;
int index,max_index,cur_bits,max_bits = 0,bit;
*n = -1;
sscanf(ip_addr,"%d.%d.%d.%d",&ip_it[0],&ip_it[1],&ip_it[2],&ip_it[3]);
ip = ((ip_it[0]<<24)+(ip_it[1]<<16)+(ip_it[2]<< 8)+ip_it[3]);
for (index = 0;net_addr_array[index][0] != '\0';index++) {
/*获取网络号和掩码*/
p = net_addr_array[index];
sscanf(p,"%d.%d.%d.%d/%d.%d.%d.%d",
&net_it[0],&net_it[1],&net_it[2],&net_it[3],
&mask_it[0],&mask_it[1],&mask_it[2],&mask_it[3]);
tar_mask = ((mask_it[0]<<24)+(mask_it[1]<<16)+(mask_it[2]<< 8)+mask_it[3]);
tar_net = ((net_it[0]<<24)+(net_it[1]<<16)+(net_it[2]<< 8)+net_it[3]);
if (((tar_mask) & (ip)) == (tar_net)) {
cur_bits = 0;
/*计算1的个数*/
for (bit = 0;bit < sizeof(tar_mask) * 8;bit++) {
cur_bits += tar_mask&1;
tar_mask >>= 1;
}
if (cur_bits > max_bits) {
max_bits = cur_bits;
max_index = index;
}
}
}
if (max_bits != 0) {
*n = max_index;
}
}
int main()
{
int i, n,arrayOut[100] = {0};
char *strIn = "ab00cd+123fght456-25 3.005fgh";
char *ip_addr = "192.168.1.100 ";
char *net_addr_array[1024] = {
"192.168.1.128/255.255.255.192",
"192.168.1.0/255.255.255.0",
"192.168.1./255.255.255.192",
"0.0.0.0/0.0.0.0",
""
};
take_num(strIn,&n,arrayOut);
printf("<1>:input:%s\noutput: [%d]\n",strIn,n);
for (i = 0;i < n;i++) {
printf("%d\n",arrayOut[i]);
}
max_prefix_match(ip_addr,net_addr_array,&n);
if (n != -1) {
printf("<2>max:[%d] %s",n,net_addr_array[n]);
}
return 0;
}
参考资料:给分