c - 以 4 个单字节解析 ip 地址字符串

标签 c parsing pic18 mplab-c18

我正在使用 C 在 MCU 上编程,我需要将包含 IP 地址的以 null 结尾的字符串解析为 4 个单字节。我用 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;
}

此代码在新行中每个字节打印 192、168、0 和 1。现在我需要单个 char 中的每个字节,例如 char byte1、byte2、byte3 和 byte4,其中 byte1 包含 1,byte4 包含 192... 或者在结构 IP_ADDR 中然后返回该结构,但我不知道如何在C.:(

最佳答案

您可以逐个字符地进行操作,就像您问题中的 C++ 版本一样。

/* 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;
}

关于c - 以 4 个单字节解析 ip 地址字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9211601/

相关文章:

c - Linux内核模块编程Makefile错误

c - 为什么 volatile 适用于 setjmp/longjmp

java - org.xml.sax.SAXParseException : The character reference must end with the ';' delimiter. 需要解决方法

Java XML 解析器执行每个节点两次

javascript - 使用 JavaScript 读取 *.csv 文件

c - 为什么这不能在 C18 中编译?

应用程序的 C Linux 带宽限制

c - PIC18F4550 的延迟功能

c - USART 在 PIC18F2550 上崩溃,我该怎么办?

c - 在 main 中使用头文件中的结构(在 C 中)