ip白名单 通过* ? 检测IP匹配 轻量级
#include "stdafx.h" #include <windows.h> #include <string.h> #include <assert.h> const int maxCount = 100; const int strMaxLen = 16; BOOLEAN IsMatchPattern(const char* ipPattern,const char* ipChar) { char* delims = "."; char* pPattern[4] = {0}; char* pIp[4] = {0}; char i = 0,j = 0;; char _ipPattern[strMaxLen] = {0}; char _ipChar[strMaxLen] = {0}; if( !ipPattern || !ipChar) return FALSE; // *字符前后只允许为.字符 if('*' == ipPattern[0] && '.' != ipPattern[1]) return FALSE; if( '*' == ipPattern[strlen(ipPattern)-1] && '.' != ipPattern[strlen(ipPattern)-2]) return FALSE; for(i = 1;i < (strlen(ipPattern)-2);i++) { if( '*' == ipPattern[i]) if( '.' != ipPattern[i-1] || '.' != ipPattern[i+1] ) return FALSE; continue; } memcpy(_ipPattern,ipPattern,strlen(ipPattern)); memcpy(_ipChar,ipChar,strlen(ipChar)); pPattern[0] =strtok(_ipPattern,delims); for(i = 1 ;i < 4;i++) { pPattern[i] =strtok(NULL,delims); } pIp[0] =strtok(_ipChar,delims); for(i = 1 ;i < 4;i++) { pIp[i] =strtok(NULL,delims); } // 分解字符串检测 按'.'分成四个子字符串 每个字符串长度不超过3 for(i = 0 ;i < 4;i++) { if(strlen(pPattern[i]) > 3) return FALSE; } for(i = 0 ;i < 4;i++) { if(strlen(pIp[i]) > 3) return FALSE; } // 检测字符串匹配 有*号则放过检测 for(i = 0;i < 4;i++) { if( memcmp((void*)(pPattern[i]),"*",1) ==0 ) { continue; } if( strlen(pPattern[i]) != strlen(pIp[i]) ) return FALSE; for(j = 0;j < strlen(pPattern[i]);j++) { char* subchPattern = pPattern[i]; char* subchIp = pIp[i]; if(subchPattern[j] != '?' && subchPattern[j] != subchIp[j]) return FALSE; } } return TRUE; } int _tmain(int argc, _TCHAR* argv[]) { char ipCheckPattern[strMaxLen] = "192.*.?2?.87"; assert( FALSE == IsMatchPattern(ipCheckPattern,"192.168.1.99") ); assert( FALSE == IsMatchPattern(ipCheckPattern,"192.168.272.87") ); assert( TRUE == IsMatchPattern(ipCheckPattern,"192.168.120.87") ); assert( TRUE == IsMatchPattern(ipCheckPattern,"192.122.223.87") ); assert( FALSE == IsMatchPattern(ipCheckPattern,"172.19.66.87") ); assert( FALSE == IsMatchPattern(ipCheckPattern,"172.0.0.87") ); assert( TRUE == IsMatchPattern(ipCheckPattern,"192.178.129.87") ); assert( FALSE == IsMatchPattern(ipCheckPattern,"192.212.17.71") ); return 0; }
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力