Determine if a string is a valid IPv4 address in C

后端 未结 15 2026
感情败类
感情败类 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:47

    int validateIP4Dotted(const char *s)
    {
        int len = strlen(s);
    
        if (len < 7 || len > 15)
            return 0;
    
        char tail[16];
        tail[0] = 0;
    
        unsigned int d[4];
        int c = sscanf(s, "%3u.%3u.%3u.%3u%s", &d[0], &d[1], &d[2], &d[3], tail);
    
        if (c != 4 || tail[0])
            return 0;
    
        for (int i = 0; i < 4; i++)
            if (d[i] > 255)
                return 0;
    
        return 1;
    }
    

提交回复
热议问题