C- IP/UDP数据包标头详细信息过滤



嗨,我正在尝试解析IP/UDP数据包的标头详细信息,实际上是为了获得时间戳,端口地址等。我知道我可以使用库来执行此操作。因此,在谷歌搜索很多之后,我发现了一个代码可以在以下方法中通过一个行数据包解析

void dump_UDP_packet(const unsigned char *packet, struct timeval ts,
                     unsigned int capture_len)
{
    struct ip *ip;
    struct UDP_hdr *udp;
    unsigned int IP_header_length;
    /* For simplicity, we assume Ethernet encapsulation. */
    if (capture_len < sizeof(struct ether_header))
    {
        /* We didn't even capture a full Ethernet header, so we
         * can't analyze this any further.
         */
        too_short(ts, "Ethernet header");
        return;
    }
    /* Skip over the Ethernet header. */
    packet += sizeof(struct ether_header);
    capture_len -= sizeof(struct ether_header);
    if (capture_len < sizeof(struct ip))
    { /* Didn't capture a full IP header */
        too_short(ts, "IP header");
        return;
    }
    ip = (struct ip*) packet;
    IP_header_length = ip->ip_hl * 4;   /* ip_hl is in 4-byte words */
    if (capture_len < IP_header_length)
    { /* didn't capture the full IP header including options */
        too_short(ts, "IP header with options");
        return;
    }
    if (ip->ip_p != IPPROTO_UDP)
    {
        problem_pkt(ts, "non-UDP packet");
        return;
    }
    /* Skip over the IP header to get to the UDP header. */
    packet += IP_header_length;
    capture_len -= IP_header_length;
    if (capture_len < sizeof(struct UDP_hdr))
    {
        too_short(ts, "UDP header");
        return;
    }
    udp = (struct UDP_hdr*) packet;
    printf("%s UDP src_port=%d dst_port=%d length=%dn",
           timestamp_string(ts),
           ntohs(udp->uh_sport),
           ntohs(udp->uh_dport),
           ntohs(udp->uh_ulen));
}

问题是,我真的不知道我应该用来调用此功能的参数,即数据包?时空空间?等等,通过聆听端口和使用recv()函数来使用套接字API接收我的数据包

for (;;)
    {
        len = sizeof(cliaddr);
        n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len);
        //sendto(sockfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
        printf("-------------------------------------------------------n");
        printf("%sn from:%s port number:%d",mesg,inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);
        printf("-------------------------------------------------------n");
    }

现在,我可以使用MESG []传递到上述功能以获取数据包详细信息,否则还有其他方法可以从特定端口接收数据包。我在时空值中使用什么价值。任何帮助对我都会有用。预先感谢

这里最相关的是如何打开套接字。您是否使用SOCK_RAW标志创建套接字?如果是,则recvfrom将接收您可以直接发送到功能的原始数据包。我不确定Windows,但是在Linux上,创建RAW套接字的代码就像::

sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));

时速参数与数据包无直接相关。这应该是您拥有数据包的时间。您将通过在recvfrom之后致电gettimeofday来获得它。

也许您应该考虑使用libpcap(数据包捕获库),tcpdump的胆量。

最新更新