C++ 用libpcap读取数据包

C++ 用libpcap读取数据包,c++,c,pcap,libpcap,packets,C++,C,Pcap,Libpcap,Packets,我正在使用pcap来监视http请求和响应。我已经设置了pcap_循环,我在回调函数中得到了数据包,但我不知道如何读取数据包内容。 这是我的回调函数: void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) { printf("%s\n", packet); } 输出总是看起来像一系列反斜杠和后面的三个数字 \200\205\300 我想知道如何使内容可读,以便查找和处

我正在使用pcap来监视http请求和响应。我已经设置了pcap_循环,我在回调函数中得到了数据包,但我不知道如何读取数据包内容。 这是我的回调函数:

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
     printf("%s\n", packet);
}
输出总是看起来像一系列反斜杠和后面的三个数字

\200\205\300

我想知道如何使内容可读,以便查找和处理http请求和响应

更新:


我的目标是读取HTTP请求和响应是否有合适且简洁的方法来执行此操作?

这是因为输出是原始二进制数据,而不是ascii字符串,所以printf只输出它直到第一个0字节。要打印数据包中的所有可读内容,请使用以下方法:

for (int i = 0; i < header->caplen; ++i) {
    if (isascii(packet[i])) {
      putchar(packet[i]);
    } else {
      putchar('.');
    }
for(int i=0;icaplen;++i){
if(isascii(包[i])){
putchar(数据包[i]);
}否则{
putchar('.');
}

这是因为输出是原始二进制数据,而不是ascii字符串,所以printf只输出它直到第一个0字节。要打印数据包中的所有可读内容,请使用以下方法:

for (int i = 0; i < header->caplen; ++i) {
    if (isascii(packet[i])) {
      putchar(packet[i]);
    } else {
      putchar('.');
    }
for(int i=0;icaplen;++i){
if(isascii(包[i])){
putchar(数据包[i]);
}否则{
putchar('.');
}

Libpcap将为您提供一个原始数据包,包括所有的头。您需要从中提取所需的数据,我建议将其转换为表示数据包的标准结构。例如

/* Start with the ether header */
ethernet = (struct ether_header *) packet;

/* Do a couple of checks to see what packet type we have */
if (ntohs (ethernet->ether_type) == ETHERTYPE_IP)
{
            // Cast it to an IP packet struct
    ip_hdr = (struct ip*)(packet + sizeof(struct ether_header));

    //If TCP...
    if(ip_hdr->ip_p == 6)
    {
               packet_info.tcp_hdr = *(struct tcphdr*)((char*)ip_hdr + sizeof(struct ip));
               // Work on extracting the actual data for HTTP stuff over here

Libpcap将给您一个原始数据包,包括所有的头。您需要从中提取所需的数据,我建议将其转换为表示数据包的标准结构。例如

/* Start with the ether header */
ethernet = (struct ether_header *) packet;

/* Do a couple of checks to see what packet type we have */
if (ntohs (ethernet->ether_type) == ETHERTYPE_IP)
{
            // Cast it to an IP packet struct
    ip_hdr = (struct ip*)(packet + sizeof(struct ether_header));

    //If TCP...
    if(ip_hdr->ip_p == 6)
    {
               packet_info.tcp_hdr = *(struct tcphdr*)((char*)ip_hdr + sizeof(struct ip));
               // Work on extracting the actual data for HTTP stuff over here

谢谢你的回答,但我正在寻找一种分离HTTP内容的方法。谢谢你的回答,但我正在寻找一种分离HTTP内容的方法。