c - pcap_next() 将地址返回到不可访问的内存区域

标签 c linux network-programming pcap

我正在编写一个 ARP 嗅探器,然后发生下一个运行时错误:

pcap_next() 函数返回指向地址空间的指针,该地址空间不可访问,仅在某些情况下会在运行时导致段错误。这是代码:

void function_arp(){
(...)

const unsigned char *frameRcv = NULL;
unsigned int byteNr = 0;
struct ether_arp *arpPack = NULL;

while (true) {
    // check on waiting time
    gettimeofday(&currentWaitTime, NULL);
    struct timeval diff = timediff(beginWaitTime, currentWaitTime);

    if (diff.tv_sec > 5) // wait for up to 5 seconds
    {
        fprintf(stderr, "Reading timed out\n");
        break;
    }

    // Receiving Frame
    byteNr = receiveRawFrame(handle, &frameRcv);
    if(frameRcv == 0x0) 
        continue;
    //when reading *frameRcv, the Segmentation fault occurs sometimes 
    fprintf(stdout, "%x - ", *frameRcv);  
    (...) 
    //The receiving of frames will be timed out after 4 sec
}

函数receiveRawFrame()的代码:

unsigned int
receiveRawFrame(struct capture_info handle, const unsigned char** receivedFrame)
{
    *receivedFrame = NULL;
    // try reading frames
    const unsigned char* frame;
    struct pcap_pkthdr pcapinfo;
    frame = pcap_next(handle.pcapHandle, &pcapinfo);

    *receivedFrame = frame;
    return pcapinfo.caplen;
}

一些注意事项:该程序将接收 IP 作为参数,并为该 IP 发送一个 ARP 请求,等待之后的回复。仅当 IP 不在本地网络中时才会发生 Segmentation Fault。在这种情况下,程序通常会超时。对于相同的输入(本地网络外的 IP),有时会发生段错误,有时不会...

我假设在 while 循环中多次调用函数 pcap_next 时发生了意外情况。

操作系统:Debian 3.2.57-3 x86_64(64 位) Pcap 版本:1.15

GDB 提供下一个输出:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401b29 in function_arp () at src/arp_impl.c:120
120                             fprintf(stdout, "%x - ", *frameRcv);

最佳答案

检查 pcap_next 的结果。仅当结果非零时,才应访问框架和信息。

关于c - pcap_next() 将地址返回到不可访问的内存区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23982477/

相关文章:

linux - 如何使用 grep 处理那些复杂的表达式?

network-programming - ns2中TCP syn攻击模拟

c++ - 网络上可变数量的参数

linux - 终端 : Is there any way to print the file names located in specific directory?

c - 在控制台中移动光标和打印字符不适用于 sleep

network-programming - Intranet 与 Internet 应用程序中的校验和验证

c - 丢失数据包(Windows NDIS 驱动程序过滤器)

c - float 不添加?

c - 如何遍历C中的结构数组?

python - python 编译C函数的问题