我目前正在编写一个 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.1
和 port = 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/