gpt4 book ai didi

c - 在 C 中使用 Netcat 时数据丢失

转载 作者:行者123 更新时间:2023-11-30 16:27:13 26 4
gpt4 key购买 nike

我有一个用于嵌入式协议(protocol)之一的 C 软件。在此,我需要将回调函数中传入的一些事件重定向到 TCP 服务器。于是,我想到了使用Netcat和系统命令。每当回调函数触发时,如果我保留一个字符串并将其转发到 netcat,那么我就会在 TCP 服务器上获取数据。但是,如果我使用回调函数中的参数构建命令,则只有第一次在 TCP 服务器上获取数据时才能看到连接成功和断开连接消息。

我的C代码是

static void zwp_avi_interfaces_alarm_report_handler(zwifd_p ifd, zwalrm_p alarm_info, time_t ts)
{

zwp_avi_interfaces_alarm_state_t *state;
zwifd_p desc_interface;

char systemcomm[1500];

char tcp_buf[100];
sprintf(tcp_buf,"echo 'node id: %d alarm type: %d alarm_event: %d", ifd->nodeid, alarm_info->ex_event, alarm_info->ex_has_sequence);
strcat(systemcomm,tcp_buf);
strcat(systemcomm," ' | netcat localhost 9091");
system(systemcomm);

}

TCP 服务器上的输出是

A new connection has been established.
Data received from client: node id: 7 alarm type: 22 alarm_event: 0

Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client
A new connection has been established.
Closing connection with the client

在代码中,如果我将最后一个系统函数调用替换为 be

system("echo 'alarm_event' | netcat localhost 9091");

然后我得到这个回调触发了多少次。 TCP服务器输出如下

A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

Closing connection with the client
A new connection has been established.
Data received from client: alarm_event

最佳答案

systemcomm 未初始化,因此 strcat(systemcomm,tcp_buf); 是未定义的行为。一切皆有可能。我们甚至可能无法理论上推测什么样的初始垃圾会导致此类症状。

如果您坚持使用系统,只需执行一个

    sprintf(systemcomm, "echo '....' | netcat localhost 9091, ....);

关于c - 在 C 中使用 Netcat 时数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52811781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com