正規表現でIPアドレス判定ーC言語ー完成
正規表現でIPアドレス判定ーC言語ーその11 - Shammerismの続きにして、IP アドレスチェック完成バージョン。
#include <ctype.h> #include <regex.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* args[]){ if( argc == 2 ){ regex_t preg; int regcompresult; regcompresult = regcomp(&preg, "^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$", REG_NOSUB | REG_EXTENDED | REG_NEWLINE); if( regcompresult == 0 ){ size_t nmatch = 0; regmatch_t pmatch[nmatch]; int regexecresult; regexecresult = regexec(&preg, args[1], nmatch, pmatch, 0); if( regexecresult == 0 ){ printf("%s is valid.\n", args[1]); } else { printf("%s is not valid.\n", args[1]); } } else { printf("Regular Expression compile failed.\n"); } } else { printf("%s is required only 1 argument.\n", args[0]); printf("Usage: %s $1\n", args[0]); } return 0; }
実行結果は以下の通り。
$ ./a.out 1.1.1.1 1.1.1.1 is valid. $ ./a.out 1.1.1.255 1.1.1.255 is valid. $ ./a.out 1.1.1.256 1.1.1.256 is not valid. $ ./a.out 1.1.1 1.1.1 is not valid. $ ./a.out a.a.a.a a.a.a.a is not valid. $ ./a.out 192.168.0.254 192.168.0.254 is valid. $ ./a.out 192.168.0.254.5 192.168.0.254.5 is not valid. $