用C语言实现ipv4地址字符串是否合法

用程序实现ipv4地址字符串是否合法,主要考察的是C字符串的操作。

搜索了下,网上没有特别好的实现,自己实现了下,见笑于大家,请指正。

 

#include <stdio.h>
#include <string.h>
int valid_ip_segment(const char* begin,
                     const char* end) {
    int len = end - begin;
    if (len < 1 || len > 4) {
        return -3; // unvalid_length
    }
    int sum = 0;
    while (begin < end) {
        if (!isdigit(*begin)) {
            return -2; // unvlaid_char
        }
        sum *= 10;
        sum += *begin - '0';
        ++begin;
    }
    if (sum > 255) {
        return -1;// unvalid_sum
    }
    return 0;
}

int valid_ip_address(const char* ip_str) {
    if (!ip_str) {
        return -1;
    }
    const char* begin = ip_str;
    const char* end = NULL;
    int seg_count = 0;
    int ret = 0;
    while ((end = strchr(begin, '.'))) {
        if ((ret = valid_ip_segment(begin, end)) < 0) {
            return ret;
        }
        ++seg_count;
        begin = end + 1;
    }
    if (seg_count != 3) {
        return -1;
    }
    end = begin;
    while(*end) {
        ++end;
    }
    return valid_ip_segment(begin, end);
}

struct TestCase {
    const char* ip_address;
    int expect_ret;
};

int main() {
    const struct TestCase test_case[] = {
        {"102.1.1.x1", -2},
        {"102.1.11.11", 0},
        {"102.1.881.1", -1},
        {"102.1.8.-1", -2},
        {"102.1.8..1", -3},
        {"102.1.1.-x3xx", -3}
    };
    size_t len = sizeof(test_case)/sizeof(test_case[0]);
    int i = 0;
    int ret = 0;
    for (;i < len; ++i ) {
        if ((ret = valid_ip_address(test_case[i].ip_address))
             != test_case[i].expect_ret) {
            printf("expect %d\t but return %d\n", test_case[i].expect_ret , ret);
        } else {
            printf("%s\t is with ret %d\n", test_case[i].ip_address, ret);
        }
    }
    return 0;
}

 

posted @ 2013-10-10 21:18  westfly  阅读(926)  评论(0编辑  收藏  举报