3、子网掩码的最大匹配前辍
#include "iostream"
#include "stdlib.h"
#include "winsock2.h"
#include "stdio.h"
#include "assert.h"
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable : 4267)
void max_prex(const char *ip_addr, const char *subnet_mask[], int len, int &n )
{
assert(ip_addr != NULL && subnet_mask != NULL && n != NULL);
unsigned long ulip = inet_addr(ip_addr);
unsigned long ulsubnet = 0;
unsigned long ulmask = 0;
n = -1; //无匹配的
const char *pstr = NULL;
char stmp[16];
int j;
for (int i = 0; i < len; i++)
{
pstr = subnet_mask[i];
memset(stmp, 0, 16);
j = 0;
if (*pstr)
{
while('/' != *pstr)
{
stmp[j++] = *pstr;
pstr++;
}
stmp[j] = '\0';
ulsubnet = inet_addr(stmp);
pstr++;
memset(stmp, 0, 16);
j = 0;
while(*pstr)
{
stmp[j++] = *pstr; pstr++;
}
stmp[j] = '\0';
ulmask = inet_addr(stmp);
}
else
{
continue;
}
//最大匹配子网
unsigned long maxfit = 0;
if ((ulip & ulmask) == ulsubnet)
{
if (ulsubnet > maxfit)
{
n = i;
maxfit = ulsubnet;
}
}
}
}
int main(int argc, char* argv[])
{
const char *ip_addr = "192.168.1.102";
const char *subnet_mask[] = {"192.168.1.0/255.255.255.0", "192.168.1.128/255.255.255.192",
"192.168.1.64/255.255.255.192", "192.168.1.96/255.255.255.224",
"192.168.1.96/255.255.255.192", "" };
int n;
int len = sizeof(subnet_mask)/4;
max_prex(ip_addr, subnet_mask, len, n);
printf("%d",n);
return 0;
}