Determine if a string is a valid IPv4 address in C

后端 未结 15 2066
感情败类
感情败类 2020-12-24 08:22

What would be a good way to determine if a string contains an IPv4 address? Should I use isdigit()?

15条回答
  •  一个人的身影
    2020-12-24 08:46

    In the url/uri rfc 3986, the Augmented Backus-Naur Form (ABNF) ipv4 address is defined as:

      IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
    
      dec-octet   = DIGIT                 ; 0-9
                  / %x31-39 DIGIT         ; 10-99
                  / "1" 2DIGIT            ; 100-199
                  / "2" %x30-34 DIGIT     ; 200-249
                  / "25" %x30-35          ; 250-255
    

    I implemented the check with regexp in the following form:

    // Although the RFC says ipv6 octects like 001 are not valid, it would be risky
    // not to accept those
    #define decoct "([01]?[0-9]?[0-9]|2[0-4][0-0]|25[0-5])"
    #define ipv4 "(" decoct "\\." decoct "\\." decoct "\\." decoct ")"
    

提交回复
热议问题