C + + to determine the legality of IP address strings __c++

Source: Internet
Author: User
Tags perl regular expression

the current solution can be grouped into the following three categories:

1. Write yourself: with '. ' Divide the IP string into substrings, and then judge whether each character of each substring is a number, and finally converts it to a value to determine whether it is in the 0~255 range.

/* Function: Determine whether the IP address is a valid interface function: Booli sipaddressvalid (const char * pszipaddr) Input: pszipaddr string output: True valid IP address, false, invalid IP address constraint: 1. Enter IP as XXX.XXX.XXX.XXX format 2. The string contains spaces that are considered legal IP 3. A space in the middle of the string is considered an illegal IP 4. Similar to 01.1.1.1, the 1.02.3.4 IP segment starts with 0 as an illegal IP 5. The child field of a single 0 is considered legal ip,0.0.0.0 is also valid I/#include <iostream> #include <cstri  
  
Ng> using namespace std; BOOL Isipaddressvalid (const char* pszipaddr) {if (!PSZIPADDR) return false;//if PSZIPADDR is null char IP1[100],CI  
    P[4];  
    int len = strlen (PSZIPADDR);  
    int i = 0,j=len-1;  
    int k, m = 0,n=0,num=0;  
    Remove the trailing space (remove the character from I-1 to j+1): while (pszipaddr[i++] = = ");  
      
    while (pszipaddr[j--] = = ");  
    for (k = i-1 k <= j+1; k++) {ip1[m++] = * (pszipaddr + k);  
      
    } Ip1[m] = ';  
  
    char *p = IP1;  
        while (*p!= ') {if (*p = = ' | | | *p< ' 0 ' | | | *p> ' 9 ') return false; cip[n++] = *p;  Saves the first character of each paragraph, which is used to determine whether the child segment is 0 beginning int sum = 0; Sum is the numeric value of each segment, between 0 and 255 while (*p!= '. ').  
          &&*p!= '] {if (*p = = ' | | *p< ' 0 ' | | | *p> ' 9 ') return false;  sum = sum * + *p-48;  
        Each segment string is converted to an integer p++; if (*p = = '. ') {if (* (* (p-1) >= ' 0 ' &&* (p-1) <= ' 9 ') && (* (p + 1) >= ' 0 ' &&* (p + 1) < = ' 9 ')//judgment "."  
                Whether there are numbers before and after, if not, then the invalid IP, such as "1.1.127."  num++; Record "."  
        The number of occurrences cannot be greater than 3 else return false;  
        }; if (Sum > 255) | | (Sum > 0 && cip[0] = = ' 0 ') | | NUM&GT;3) return false;//The value of Jozo segment >255 or 0 or "." that starts with 0.  
        The number of >3, then the invalid IP if (*p!= ' ") p++;  
    n = 0;  
    if (Num!= 3) return false;  
return true;  
    } void Main () {char ip[] = "254.1.1.1";  
    Char ip[100];  
    Cin >> IP;  
    BOOL tf = Isipaddressvalid (IP); cout &Lt;< tf<<endl;  
System ("pause");   }

Other people give a solution is also very good, take full advantage of the characteristics of the Atoi function: when there is a character, only the number of characters before the conversion, and then move the string array pointer backward.

2. Use the inet_addr (const char * str) function. The function of inet_addr () is to convert a decimal-point IP into a long integer (u_long type). Throw to this function a string, can successfully convert is a valid IP address string, conversion failed to return Inaddr_none. If a non-standard form of IP address is not allowed, add the right '. ' The number of the judge. In addition, the Inaddr_none is 255.255.255.255, so this address string cannot be converted correctly.

3, the use of regular expressions. This writing code is efficient and easy to ensure correctness, but also easy to maintain. Need to use the Regex library in boost. The only downside is that this is a static link library that is slower to compile and will increase in size when packaged.

BoostTest.cpp: Defines the entry point for a console application.  
//  
  
#include "stdafx.h"  
#include <iostream>     
#include <boost/xpressive/xpressive_ dynamic.hpp>  
  
//boost Verify IP address legal  
bool Checkip (const char *ip)  
{using namespace boost with regular expressions:  
    : xpressive;  
    /* Define Regular Expressions */  
    Cregex reg_ip = Cregex::compile ("25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[ 1-9][0-9]| [1-9]) [.] (25[0-5]|2[0-4][0-9]|1[0-9][0-9]| [1-9] [0-9]| [0-9]) [.] (25[0-5]|2[0-4][0-9]|1[0-9][0-9]| [1-9] [0-9]| [0-9]) [.] (25[0-4]|2[0-4][0-9]|1[0-9][0-9]| [1-9] [0-9]| [1-9]);   
    return  regex_match (IP, reg_ip);  
  
int _tmain (int argc, _tchar* argv[])    
{    
    std::wcout<< "IP:" <<checkip ("1247.0.0.1");  
  
    GetChar ();    
    return 0;    
}  

Perl regular-expression syntax
Perl Regular expression syntax can be found in chapters 7th, 8, 9, or boost's documentation for the introduction to Perl language. The syntax listed here is not comprehensive, and some of the instructions may not be clear.

. Any character, which does not match the null character when using the MATCH_NO_DOT_NULL flag; Do not match newline characters when using Match_not_dot_newline

^ Match start of line
$ match end of line
* Repeat 0 times or more, for example a*b can be matched B,ab,aab,aaaaaaab
+ Repeat more than once, for example a+b can match Ab,aab,aaaaaaaab. But it doesn't match B.
? 0 times or once, such as Ca?b match cb,cab but not Caab
A{n} match character ' A ' repeats n times
A{n,}, character a repeats more than n times (including n times)
A{n,m} a repeats N to M times (incl.)

*? Match the previous atom more than 0 times
+? Match the previous atom more than once
?? Match the previous atom more than 0 times
{N,}? Match previous Atom n times above (incl.)
{n,m? Match before an atom N to M times (including)

| Or operations, such as AB (D|EF) matching Abd or abef
[] Character set operations, such as [ABC] will match any single character ' A ', ' ' A ', ' ' B ', ' ' C '
[A-d], representing A, B, C, D
^ No action, for example [^a-c] represents all characters from A to C

4, swscanf () function, simple and efficient

BOOL isipformatright (LPTSTR ipaddress)
{//Determine whether the IP address is legal
int a,b,c,d;
if ((SWSCANF (ipaddress,l "%d.%d.%d.%d", &a,&b,&c,&d) ==4)
&& (a>=0&&a<= 255)
&& (b>=0&&b<=255)
&& (c>=0&&c<=255)
&& (d >=0&&d<=255))
{return
TRUE;
}
return FALSE;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.