基于libpcap的程序分析出的网络数据,建立链表的问题?
思想: 把分析出的SIP,DIP链接成一个指针链表,这样的话可以用于后续的处理(如:把SIP,DIP相同的包合在一起)
代码:
//struct outputbuf 是一个结构体,和struct ip差不多,为了节省篇幅,很判断性的东西我就删掉了,不知会否影响阅读?
void myHandle_IP(struct ip *iphdr,struct pcap_pkthdr pkthdr,const char *packet,struct outputbuf *op_buf)
{
op_buf->b_saddr = inet_ntoa(iphdr->ip_src);
op_buf->b_daddr = inet_ntoa(iphdr->ip_dst);
}
struct outputbuf *myWrite_BUF(struct outputbuf *head,struct outputbuf *op_Wbuf)
{
struct outputbuf *p1,*p2,*p3;
p1 =p3 = head;
p2 = op_Wbuf;
if(head==NULL)
{
head = p2;
p2->next = NULL;
}
else
{
p1->next = p2;
p2->next=NULL;
k = k+1;
}
do
{
printf( "%15s %15s\n",(p3->b_saddr),(p3->b_daddr);
p3 = p3->next;
}while(p3!=NULL);
return(head);
}
int main()
{
const char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t* descr;
const u_char *packet;
struct pcap_pkthdr hdr; /* pcap.h */
struct ether_header *eptr; /* net/ethernet.h */
struct ip *ip; /* netinet/ip.h */
u_char *ptr; /* printing out hardware header info */
u_int16_t ethertype;
struct outputbuf *head = NULL;
dev = pcap_lookupdev(errbuf); /* grab a device to peak into... */
descr = pcap_open_live(dev,65535,0,60,errbuf);
for( ; ; )
{
packet = pcap_next(descr,&hdr); //不停的读取网络数据包
eptr = (struct ether_header *) packet;
ethertype = eptr->ether_type;
if(ntohs(ethertype) == ETHERTYPE_IP)
{
struct outputbuf *op_buf = (struct outputbuf *)malloc(sizeof(struct outputbuf )); /*must assign memory*/
ip = (struct ip*)(packet + sizeof(struct ether_header)); /*check to see we have a packet of valid length*/
myHandle_IP(ip,hdr,packet,op_buf);
head = myWrite_BUF(head,op_buf);
}
}
free(head);
}
输出结果:
[root@yqlyd root]# gcc test.c -o test.o -lpcap
[root@yqlyd root]# ./test.o
61.152.144.43 61.152.144.43 //这里还没有解决之前的问题,输出相同的IP地址
172.16.10.170 172.16.10.170
172.16.10.170 172.16.10.170
172.16.10.170 172.16.10.170
172.16.10.170 172.16.10.170
......
请问仁兄: 这个链表为什么是这个样子? 最多只有两个结点, 而且内容也不对.