写个程序,需要处理ip字符串,在做合法性校验的时候感觉太麻烦,于是想到了正则。看了一下手册,试用一下。
1 源码 检测ipv4字符串的合法性
- #include <sys/types.h>
- #include <regex.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define IP_PATTERN "^([0-9]|[1-9][0-9]|1[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9]{1,2}|2[0-4][0-9]|25[0-5])$"
- static void regex_emsg(int errorcode, regex_t *preg);
- int main(int argc, char *argv[])
- {
- regex_t reg;
- regmatch_t match[5];
- int retval;
- if (argc != 2) {
- fprintf(stderr, "usage: %s \n"
- "example: %s 1.2.3.4\n",
- argv[0], argv[0]);
- exit(EXIT_FAILURE);
- }
- retval = regcomp(®, IP_PATTERN, REG_EXTENDED | REG_NEWLINE);
- if (retval != 0)
- regex_emsg(retval, ®);
- retval = regexec(®, argv[1], sizeof match / sizeof match[0], match, 0);
- printf("%s is %s\n", argv[1], retval == 0 ? "legal" : "illegal");
- regfree(®);
- /*
- * 如果是正确的ip, 输出详细的匹配过程
- */
- if (retval == 0) {
- int i;
- for (i = 1; i < sizeof match / sizeof match[0]; i++) {
- printf("ip part[%d]: %.*s\n", i, match[i].rm_eo - match[i].rm_so,
- argv[1] + match[i].rm_so);
- }
- }
- exit(EXIT_SUCCESS);
- }
- /*
- * 输出regexXXX调用出错消息
- */
- static void regex_emsg(int errorcode, regex_t *preg)
- {
- char msg[512] = {'\0'};
- regerror(errorcode, preg, msg, sizeof msg - 1);
- fputs(msg, stderr);
- fputc('\n', stderr);
- return;
- }
- /* filename: regex_checkip.c */
-
将上面代码编译gcc -Wall regex_checkip.c -o checkip
-
运行下面的测试基本test.sh ./checkip
2 测试脚本 - #!/bin/sh
- # filename: test.sh
- $1 0.0.0.0
- echo ""
- $1 1.1.1.1
- echo ""
- $1 255.255.255.255
- echo ""
- $1 a1.1.1.1
- echo ""
- $1 1.1.1.1b
- echo ""
- $1 256.255.255.255
- echo ""
- $1 1.23.234.0
- echo ""
- $1 a.b.sd.d
- echo ""
- $1 192.168.54.48
- echo ""
3 测试结果
- 0.0.0.0 is legal
- ip part[1]: 0
- ip part[2]: 0
- ip part[3]: 0
- ip part[4]: 0
- 1.1.1.1 is legal
- ip part[1]: 1
- ip part[2]: 1
- ip part[3]: 1
- ip part[4]: 1
- 255.255.255.255 is legal
- ip part[1]: 255
- ip part[2]: 255
- ip part[3]: 255
- ip part[4]: 255
- a1.1.1.1 is illegal
- 1.1.1.1b is illegal
- 256.255.255.255 is illegal
- 1.23.234.0 is legal
- ip part[1]: 1
- ip part[2]: 23
- ip part[3]: 234
- ip part[4]: 0
- a.b.sd.d is illegal
- 192.168.54.48 is legal
- ip part[1]: 192
- ip part[2]: 168
- ip part[3]: 54
- ip part[4]: 48
感觉用着还可以。:-)
阅读(1850) | 评论(0) | 转发(0) |