1
我想写一个简单的应用程序来输出dst和src TCP端口号。为了测试,我尝试应用pcap过滤器来仅侦听端口80或来自端口80的数据包。但是,尽管所有内容对我来说都是正确的,但我始终得到端口号为0的端口号。大约10%的时间我得到了5位数的端口号。任何人都可以给我任何提示,我可能会做错什么?偶尔的TCP头部端口号0
#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);
}