linux tcpdump C++代码
时间: 2023-10-20 13:07:42 浏览: 159
Linux_Network_Programming.rar_linux c语言
以下是一个简单的 Linux tcpdump C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv)
{
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp;
char filter_exp[] = "port 80";
bpf_u_int32 mask;
bpf_u_int32 net;
// Open the pcap device
if ((adhandle = pcap_open_live("eth0", 65536, 1, 1000, errbuf)) == NULL)
{
fprintf(stderr, "Unable to open the adapter: %s\n", errbuf);
exit(EXIT_FAILURE);
}
// Compile and apply the filter
if (pcap_compile(adhandle, &fp, filter_exp, 0, net) == -1)
{
fprintf(stderr, "Error compiling filter expression\n");
exit(EXIT_FAILURE);
}
if (pcap_setfilter(adhandle, &fp) == -1)
{
fprintf(stderr, "Error setting filter\n");
exit(EXIT_FAILURE);
}
// Start capturing packets
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
// Process the packet data here
printf("Packet captured.\n");
}
```
该代码打开一个名为 "eth0" 的网卡设备,并使用过滤器仅捕获端口号为 80 的流量。在 packet_handler() 函数中,您可以处理捕获到的数据包。在本例中,该函数简单地打印一条消息。
阅读全文