c - Linux sscanf 函数不填充变量

标签 c linux parsing scanf

我目前正在编写一个 FTP 服务器,我需要从输入字符串缓冲区中解析远程服务器的 IP 和端口,格式如下:

xxx,xxx,xxx,xxx,yyy,zzz

地点:

  • xxx 代表十进制的 IP 地址八位字节
  • yyy 为 round((远程端口号)/256)
  • zzz 是(远程端口号)% 256

例如:127,0,0,1,123,64 表示 ip = 127.0.0.1port = 31552

我当前正在使用 sscanf 从输入字符串缓冲区中提取以下字段:

sscanf(str, "%u,%u,%u,%u,%u,%u", ret_ip, &ip[0], &ip[1], &ip[2], &temp1, &temp2) == 6

地点:

  • str 是输入缓冲区
  • ret_ip 的类型为 uint32_t
  • ip 的类型为 uint32_t
  • temp1 和 temp2 的类型为 unsigned Short int

示例代码:

#include <stdio.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
    uint32_t ip[4];
    unsigned short int temp, temp1;

    if (sscanf("127,0,0,1,142,214", "%u,%u,%u,%u,%u,%u", &ip[0], &ip[1], &ip[2], &ip[3], &temp, &temp1) == 6)
    {
        printf("%u : %u", temp, temp1);
    }

    return (0);
}

我的问题是,对于有效字符串,temp1 的值始终为 0(零),即除 temp1 之外的所有其他变量均根据字符串填充。我将不胜感激任何帮助。

最佳答案

scanf 不像 printf 那样容忍格式说明符不匹配。说明符需要完全匹配,否则您将调用未定义的行为。

对于无符号短,请使用%hu%u 代表 unsigned int

对于像uint32_t这样的类型没有直接的格式说明符。您需要use a macro from inttypes.h :“%”SCNu32

一起:

if (sscanf(str, "%" SCNu32 ",%" SCNu32 ",%" SCNu32 ",%" SCNu32 ",%hu,%hu", ret_ip, &ip[0], &ip[1], &ip[2], &temp1, &temp2) == 6)

关于c - Linux sscanf 函数不填充变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540008/

相关文章:

c - 在 Assembly Works 中如何调用带有大量参数的函数

python - Scrapy爬取同一页面上的多个XPathSelector

c - 将字符串解析为单独的字符串

c - 函数返回一些指针为 NULL

c - Ruby 无法加载 DLL

c - 仅保留数据结构的少量更改

linux - 由于缺少 uuid 开发包导致 Asterisk 配置错误

linux - 在/var/log/messages中,: Watching system buttons [.是什么..] Power Button

java - 用于创建、解析和查询 XML 的最佳 Java 库

c++ - 使用 SCHED_RR 调度策略运行的线程的 sched_yield() 的影响