我的Ubuntu虚拟机的IP地址是192.168.1.110。其他一切都很好。我不知道代码有什么问题。也许我正在使用错误的包头结构? 下面是我的代码和输出。我的主机IP应该是192.168.1.110,现在的端口肯定是错误的。从libpcap捕获的数据包中获取错误的ip和端口号
sudo ./sniffall 0
84.72.137.105:38055 192.168.1.105:56652
192.168.1.105:56652 174.141.213.124:28073
84.72.137.105:38055 192.168.1.105:56652
192.168.1.105:56652 174.141.213.124:28073
84.72.137.105:38055 192.168.1.105:56652
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>
#include <netinet/ether.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
void getPacket(u_char *args, const struct pcap_pkthdr *pkthdr, const u_char *packet){
struct ip *ip;
struct tcphdr *tcp;
ip = (struct ip*)(packet+sizeof(struct ether_header));
tcp = (struct tcphdr*)(packet+sizeof(struct ether_header)+sizeof(struct ip));
char* src = inet_ntoa(ip->ip_src);
printf("%s:%d ",src,tcp->source);
char* dst = inet_ntoa(ip->ip_dst);
printf(" %s:%d\n", dst, tcp->dest);
}
int main(int argc, char *argv[]){
char errbuf[PCAP_ERRBUF_SIZE], *device;
device = argv[1];
pcap_t *handle;
handle = pcap_open_live(device, BUFSIZ, 1, 1000, errbuf);
if(!handle){
device = pcap_lookupdev(errbuf);
handle = pcap_open_live(device, BUFSIZ, 1, 1000, errbuf);
if(!handle){
printf("Couldn't open device %s: %s\n", device, errbuf);
}
}
pcap_loop(handle, 5, getPacket, NULL);
return 0;
}
您正在打开混杂模式下的pcap手柄。也许你看到电线上的其他交通? – pilcrow
这看起来不像你程序的输出。它不是打印':'后面跟着端口号。您还应该使用'ntohs'将端口号从网络转换为主机字节顺序。 – Barmar
你有一大块代码被注释掉了。如果不需要的话,那对于试图帮助回答你的问题的人来说只是噪音:-)只是一个友好的笔记! – corsiKa