我正在尝试编写一个简单的应用程序来输出 dst 和 src TCP 端口号。为了测试,我尝试应用 pcap 过滤器来仅嗅探进出端口 80 的数据包。但是,尽管一切看起来对我来说都是正确的,但我一直得到端口号 0。大约 10% 的时间我得到一个 5 位数的端口号。谁能给我任何提示我可能做错了什么?
#include<pcap.h>
#include<stdio.h>
#include<net/ethernet.h>
#include<netinet/ip.h>
#include<netinet/tcp.h>
#include<arpa/inet.h>
void handle_packet(u_char* args, const struct pcap_pkthdr* pkthdr, const u_char* p)
{
struct iphdr* ip_hdr;
struct tcphdr* tcp_hdr;
ip_hdr = (struct iphdr*) (p+sizeof(struct ether_header));
tcp_hdr = (struct tcphdr*) (ip_hdr+sizeof(struct iphdr));
printf("src:%d\n", ntohs(tcp_hdr->source));
printf("dst:%d\n", ntohs(tcp_hdr->dest));
}
int main(int argc, char** argv)
{
pcap_t *handle; /* Session handle */
char *dev; /* The device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
struct bpf_program filter; /* The compiled filter */
char filter_app[] = "tcp port 80"; /* The filter expression */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
/* Define the device */
dev = pcap_lookupdev(errbuf);
/* Find the properties for the device */
pcap_lookupnet(dev, &net, &mask, errbuf);
/* Open the session in promiscuous mode */
handle = pcap_open_live(dev, BUFSIZ, 0, 0, errbuf);
/* Compile and apply the filter */
pcap_compile(handle, &filter, filter_app, 0, net);
pcap_setfilter(handle, &filter);
pcap_loop(handle, 10, handle_packet, NULL);
pcap_close(handle);
return(0);
}