在4个单字节解析IP地址字符串 [英] parsing ip adress string in 4 single bytes

查看:547
本文介绍了在4个单字节解析IP地址字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用C MCU编程和我需要解析包含IP地址到4个单字节的空终止字符串。我做了一个例子用C ++:

I'm programming on a MCU with C and I need to parse a null-terminated string which contains an IP address into 4 single bytes. I made an example with C++:

#include <iostream>
int main()
{
    char *str = "192.168.0.1\0";
    while (*str != '\0')
    {
            if (*str == '.')
            {
                    *str++;
                    std::cout << std::endl;
            }
            std::cout << *str;
            *str++;
    }
    std::cout << std::endl;
    return 0;
}

这code打印192,168,0和1在一个新行的每个字节。现在我需要在单个字符的每个字节,比如CHAR字节1,字节2,字节3字节4和那里字节1包含1个字节4和192包含...或者在结构IP_ADDR并返回该结构的话,但我不知道该怎么做的C.:(

This code prints 192, 168, 0 and 1 each byte in a new line. Now I need each byte in a single char, like char byte1, byte2, byte3 and byte4 where byte1 contains 1 and byte4 contains 192... or in a struct IP_ADDR and return that struct then, but I dont know how to do it in C. :(

推荐答案

您可以做到这一点字符逐个字符,如你的问题做了C ++版本。

You can do it character-by-character, as does the C++ version in your question.

/* ERROR CHECKING MISSING */
#include <ctype.h>
#include <stdio.h>
int main(void) {
    char *str = "192.168.0.1", *str2;
    unsigned char value[4] = {0};
    size_t index = 0;

    str2 = str; /* save the pointer */
    while (*str) {
        if (isdigit((unsigned char)*str)) {
            value[index] *= 10;
            value[index] += *str - '0';
        } else {
            index++;
        }
        str++;
    }
    printf("values in \"%s\": %d %d %d %d\n", str2,
              value[0], value[1], value[2], value[3]);
    return 0;
}

这篇关于在4个单字节解析IP地址字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆