C语言,MAC地址、IP地址、IPv6地址字符串转换成数组

#include 
#include 
#include 

#define     ipaddr      "192.16.100.20"         // dotted decimal
#define     ip6addr     "2019:1255:1232::1:1"     // colon hexadecimal
#define     macaddr     "00-11-22-33-44-FF"

int macstr_parse(const char *point, unsigned char result[6]) {
    for (int i = 0; i < 6; i++) {
        result[i] = 0xfe;
    }
    char buf[18] = {0}, p = 0, q = 0;
    strcpy(buf, point);
    buf[strlen(point)] = '-';
    for(int i = 0;i < 6; i++) {
        q = strchr(buf+p, '-') - buf;
        buf[q] = '\0';
        result[i] = strtol(buf+p, NULL, 16);
        p = q + 1;
    }
    return 1;
}

int ip4str_parse(const char *point, unsigned char result[4]) {
    for (int i = 0; i < 4; i++) {
        result[i] = 0;
    }
    char buf[18] = {0}, p = 0, q = 0;
    strcpy(buf, point);
    buf[strlen(point)] = '.';
    for(int i = 0;i < 4; i++) {
        q = strchr(buf+p, '.') - buf;
        buf[q] = '\0';
        result[i] = strtol(buf+p, NULL, 10);
        p = q + 1;
    }
    return 1;
}

int ip6str_parse(const char *point, unsigned int result[4]) {
    for (int i = 0; i < 4; i++) {
        result[i] = 0;
    }
    char buf[40] = {0}, revbuf[40], p = 0, q = 0;
    strcpy(buf, point);
    strcpy(revbuf, point);
    strrev(revbuf);
    buf[strlen(point)] = ':';
    revbuf[strlen(point)] = ':';
    for(int i = 0;i < 8; i++) {
        q = strchr(buf+p, ':') - buf;
        buf[q] = '\0';
        if (i % 2 == 0) {
            result[i/2] = 0;
            result[i/2] = strtol(buf+p, NULL, 16)<<16;
        } else {
            result[i/2] += strtol(buf+p, NULL, 16);
        }
        p = q + 1;
        // if we find  ::, then we should scan revbuf.2019:1::1 1::1:2019
        if (buf[p] == ':') {
            p = q = 0;
            for (int j = 7;j > i;j--) {
                q = strchr(revbuf+p, ':') - revbuf;
                revbuf[q] = '\0';
                strrev(revbuf+p);
                if (j % 2 == 0) {
                    result[j/2] += strtol(revbuf+p, NULL, 16)<<16;
                } else {
                    result[j/2] = 0;
                    result[j/2] += strtol(revbuf+p, NULL, 16);
                }
                p = q + 1;
                if (revbuf[p] == ':') {
                    break;
                }
            }
            break;
        }
    }
    return 1;
}
int main() {
    unsigned char ip4[4];
    unsigned int ip6[4];
    unsigned char macaddr1[6];

    ip4str_parse(ipaddr, ip4);
    ip6str_parse(ip6addr, ip6);
    macstr_parse(macaddr, macaddr1);

    for (int i = 0;i < 4 ; i++) {
        printf("%d\r\n",ip4[i]);
    }

    for (int i = 0;i < 4 ; i++) {
        printf("%p\r\n",ip6[i]);
    }
    for (int i = 0;i < 6 ; i++) {
        printf("%d\r\n",macaddr1[i]);
    }
    return 0;
}

结果: 

C语言,MAC地址、IP地址、IPv6地址字符串转换成数组_第1张图片

 

你可能感兴趣的:(c语言,字符转换,数组,IP,地址)