首页 > 代码库 > ip白名单 通过* ? 检测IP匹配 轻量级
ip白名单 通过* ? 检测IP匹配 轻量级
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #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; } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。