【问题标题】:How to save in C the tcpdump results in a file?如何将 tcpdump 结果保存在 C 文件中?
【发布时间】:2021-10-08 10:09:21
【问题描述】:

我正在编写一个 C 程序来在我的设备上执行 tcpdump。我正在使用 C 中的命令作为普通终端命令执行 system("找出为什么这不符合我的想法");无论如何,我想将结果保存在一个文件中 我想将结果保存在一个文件中,该文件的名称由 C 中的变量指示。我该怎么做?这是我的代码:(变量是file_name,这是包含我要保存结果的文件名的变量)

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


int main() {

    char string_year[20];
    char string_month[20];
    char string_day[20];
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    //printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
    int year = tm.tm_year + 1900;
    int month = tm.tm_mon + 1;
    int day = tm.tm_mday;
    //printf("%d\n", year);
    sprintf(string_year, "%d", year);
    //printf("%s\n", string_year);
    //printf("%d\n", month);
    sprintf(string_month, "%d", month);
    //printf("%s\n", string_month);
    //printf("%d\n", day);
    sprintf(string_day, "%d", day);
    //printf("%s\n", string_day);
    char file_name[80];
    strcat(file_name, string_day);
    strcat(file_name, "_");
    strcat(file_name, string_month);
    strcat(file_name, "_");
    strcat(file_name, string_year);
    strcat(file_name, ".pcap");
    printf("%s\n", file_name);


    system("tcpdump -i eth0 -w file_name");
    return 0;

}

【问题讨论】:

  • char cmd[128]; snprintf(cmd, sizeof(cmd), "tcpdump -i eth0 -w %s", file_name); system(cmd);
  • 无论你在做什么,最好只写一个 Bash 脚本或单行。 tcpdump -i eth0 -w "$(date "+%m_%d_%Y.pcap")"
  • 一个 shell 脚本似乎是一个不错的选择,而不是一个 C 程序......如果你想以编程方式管理 tcpdump 的输出,你可以使用 C 函数popen,这个函数可以让你得到一个执行程序的每行输入!同样,要以编程方式进行分析,您可以编写一个过滤器 I.E. tcpfilter 与 C 然后你可以从命令行执行类似 `tcpdump -i eth0 | tcpfilter`.

标签: c string variables system tcpdump


【解决方案1】:
char system_input[100];
sprintf(system_input, "tcpdump -i eth0 -w %s", file_name);
system(system_input);

【讨论】:

  • 您的代码是一个正确的解决方案,但如果我将这 3 行插入到我的代码中,并尝试用“touch”替换“tcpdump -i eth0 -w”(仅查看 file_name 是否正确),这是我在文件夹中的文件名。 '�'$'\003''3_8_2021.pcap' .... 你知道为什么吗?
  • char file_name[80]; strcat(file_name - file_name 没有被初始化,所以你不能strcat 到它。使用零终止符或strcpy 对其进行初始化。但总的来说,只是snprintf 而不是strcat。并且不要使用sprintf - 使用snprintf
【解决方案2】:

放置在file_name[] 中的第一项必须通过strcpy() 完成-或- 通过file_name[0] = '\0' 完成

然后可以通过strcat()追加所有其他数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多