糖果实验室杂货铺

Candy Lab

libpcap监听网络端口数据

3 weeks ago 0

下面的代码是监听本机源80地址流出的数据, 并以字符的形式打印出来。

代码:

None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <pcap.h>  
#include <time.h>  
#include <stdlib.h>  
#include <stdio.h>  
  
void getPacket(u_char * arg, const struct pcap_pkthdr * pkthdr, const u_char * packet)  
{  
  int * id = (int *)arg;  
    
  printf("id: %d\n", ++(*id));  
  printf("Packet length: %d\n", pkthdr->len);  
  printf("Number of bytes: %d\n", pkthdr->caplen);  
  printf("Recieved time: %s", ctime((const time_t *)&pkthdr->ts.tv_sec));   
    
  int i;  
  for(i=0; i<pkthdr->len; ++i)  
  {   
    //printf(" %02x", packet[i]);  
    printf(" %c", packet[i]);  
    if( (i + 1) % 16 == 0 )   
    {   
        //printf("\n");  
    }   
  }   
  
  //printf("%s\n", packet);

  printf("\n\n");  
}  


int main()  
{  
  char errBuf[PCAP_ERRBUF_SIZE], * devStr;  
    
  /* get a device */  
  //devStr = pcap_lookupdev(errBuf);  
  devStr = "eth1";
    
  if(devStr)  
  {   
    printf("success: device: %s\n", devStr);  
  }   
  else  
  {   
    printf("error: %s\n", errBuf);  
    exit(1);  
  }   
    
  /* open a device, wait until a packet arrives */  
  pcap_t * device = pcap_open_live(devStr, 65535, 1, 0, errBuf);  
    
  if(!device)  
  {   
    printf("error: pcap_open_live(): %s\n", errBuf);  
    exit(1);  
  }   
    
  /* construct a filter */  
  struct bpf_program filter;  
  pcap_compile(device, &filter, "src port 80", 1, 0);  
  //pcap_compile(device, &filter, "dst port 80", 1, 0);  
  pcap_setfilter(device, &filter);

  /* wait loop forever */
  int id = 0;
  pcap_loop(device, -1, getPacket, (u_char*)&id);

  pcap_close(device);

  return 0;
}

编译:

1
gcc test.c -o test -lpcap

糖果实验室

Openresty中文编程网
IKBC经典机械键盘
机械键盘领券优惠购买

Write a Comment