(原創) 如何檢查是否為合法IP? (.NET) (C++/CLI) (C/C++) (Reqular Expression)
Abstract
檢查是否為合法IP,不需hardcode了,透過Regular Expression,只要一行就可以。
Introduction
有網友Email問我如何用C++/CLI檢查IP,當然自己parse也可以,不過既然用了.NET平台,而.NET又支援Regular Expression,這種檢查的字串的程式,用Regular Expression是首選。
C++/CLI / CheckIP.cpp
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : ChcekIP.cpp
5
Compiler : Visual C++ 8.0 / C++/CLI
6
Description : Demo how to validate IP
7
Release : 05/17/2007 1.0
8
*/
9
#include "stdafx.h"
10
using namespace System;
11
using namespace System::Text::RegularExpressions;
12
13
bool isValidIP(String^ const% ip) {
14
Regex^ reg = gcnew Regex("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
15
Match^ match = reg->Match(ip);
16
17
return match->Success;
18
}
19
20
int main() {
21
String^ s1 = "140.290.1.1";
22
String^ s2 = "140.113.1.1";
23
24
Console::WriteLine(isValidIP(s1));
25
Console::WriteLine(isValidIP(s2));
26
}

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

執行結果


Reference
Sample Regular Expressions