C语言从一段字符串中提取IP地址的方法

1. 需求

当前待解析字符串格式为:

+CIFSR:STAIP,<Station	IP	address>
+CIFSR:STAMAC,<Station	MAC	address>

某次通信具体的数据内容为:

+CIFSR:STAIP,"0.0.0.0"
+CIFSR:STAMAC,"98:f4:ab:da:a6:7f"

要从中提取出ip地址目标字符串[0.0.0.0]。

2. 实现方法

① 利用strstr找到固定头部;

② 利用sscanf提取具体数值;

3. 实现代码

#include <stdio.h>
#include <string.h>

char src_str[100] = "+CIFSR,STAIP:\"122.51.89.94\"\r\n"; 

int seg1,seg2,seg3,seg4;

int main(void)
{
    char hostip[15];

    char *str = strstr(src_str, "STAIP");

    printf("str is [%s]\r\n", str);

    sscanf(str+strlen("STAIP:"), "\"%d.%d.%d.%d\"", &seg1, &seg2, &seg3, &seg4);

    sprintf(hostip, "%d.%d.%d.%d", seg1, seg2, seg3, seg4);

    if (!hostip) {
        printf("parser fail\r\n");
    } else {
        printf("parser success, host ip is:%s\r\n", hostip);
    }
    
    return 0;
}

编译:

gcc test.c -o test.exe

执行:

猜你喜欢

转载自blog.csdn.net/Mculover666/article/details/107974084