gpt4 book ai didi

C recvfrom 破坏系统日志

转载 作者:行者123 更新时间:2023-11-30 17:42:30 25 4
gpt4 key购买 nike

我最近用 C 语言编写了一个 netflow 接收器,它通过 UDP 监听 netflow。一旦处理完流数据报,它就会将其写入系统日志。我的问题是,一旦我收到带有标准 recvfrom 函数的数据报包,我的消息就不再进入系统日志。我接收和处理数据很好,但系统日志写入不起作用。代码如下所示

setlogmask(LOG_UPTO(LOG_NOTICE));
openlog("netflow_receiver", LOG_CONS, LOG_LOCAL2);
syslog(LOG_NOTICE, "Syslogger started");

while(1){

syslog(LOG_NOTICE, "Top of loop");
unsigned char* mesg = (unsigned char*)malloc(1024 * sizeof(unsigned char));
syslog(LOG_NOTICE, "Allocated message memory");

len = sizeof(cliaddr);
syslog(LOG_NOTICE, "Got len of client");

//Syslog stops after this
n = recvfrom(sockfd, mesg, 1024, 0, (struct sockaddr *) &cliaddr, &len);
syslog(LOG_NOTICE, "received");
mesg[n] = 0;

syslog(LOG_NOTICE, "Calling log_record");
process_record(mesg);
syslog(LOG_NOTICE, "Back from log_record");

}

系统日志看起来就像这样

Dec 12 09:42:01 my_pc netflow_receiver: Syslogger started
Dec 12 09:42:01 my_pc netflow_receiver: Top of loop
Dec 12 09:42:01 my_pc netflow_receiver: Allocated message memory
Dec 12 09:42:01 my_pc netflow_receiver: Got len of client
Dec 12 09:48:33 my_pc netflow_receiver: Syslogger started
Dec 12 09:48:33 my_pc netflow_receiver: Top of loop
Dec 12 09:48:33 my_pc netflow_receiver: Allocated message memory
...

任何想法或建议...如果有人知道一个好的库,我愿意使用非标准 C 系统日志库。

最佳答案

mesg[n] = 0; is wrong

如果 recvfrom 返回 1024,则说明您正在对内存进行索引,超出了应有的范围。

如果recvfrom返回-1,同样的事情。

确保您处理了这两种情况。

您需要确保 sockfd 实际上具有正确的套接字值,syslog 也会打开套接字,如果您在某处出现错误并开始从该文件描述符读取,则会发生奇怪的事情。

关于C recvfrom 破坏系统日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20541013/

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