pcap 3

来源:互联网 发布:怎样把淘宝网放到桌面 编辑:程序博客网 时间:2024/06/16 09:48

#include <stdio.h>
#include <pcap.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void)
{
 char *net_dev;
 char *ip_addr;
 char *net_mask;
 char errbuf[PCAP_ERRBUF_SIZE];

 bpf_u_int32 netp;
 bpf_u_int32 maskp;
 struct in_addr addr;
// 返回一个设备名,Linux可能是eth1,
Mac OS X可能是en0,错误时返回NULL。
参数errbuf是遇到错误时对错误的描述字符串,我们一般这么定义:
 net_dev=pcap_lookupdev(errbuf);
 if(net_dev==NULL){
  printf("cannot get the network device info: %s\n",errbuf);
  return 1;
 } 
        printf("the network device is: %s\n",net_dev);
//获得IP地址和子网掩码
 if(pcap_lookupnet(net_dev,&netp,&maskp,errbuf)==-1){
  printf("cannot get the network device ip info:%s\n",errbuf);
  return 1;
 }

 addr.s_addr=netp;
 ip_addr=inet_ntoa(addr);

 if(ip_addr==NULL){
  printf("convert network address fail\n");
  return 1;
 }
        printf("ip address is : %s\n",ip_addr);

 addr.s_addr=maskp;
 net_mask=inet_ntoa(addr);

 if(net_mask==NULL){
  printf("convert network mask fail\n");
  return 1;
 }

 printf("network mask is : %s\n",net_mask);

 return 0;
}

#include <stdio.h>
#include <pcap.h>
#include <netinet/if_ether.h>

int main(void)
{
 pcap_t *sniffer_des;
 char errbuf[PCAP_ERRBUF_SIZE];
 char *net_dev;
 bpf_u_int32 netp;
 bpf_u_int32 maskp;
 struct bpf_program fp;
 const u_char *packet;
 struct pcap_pkthdr hdr;
 struct ether_header *eth_header;
 u_char *ptr;
 
 char filter_exp[]="port 22";

 net_dev=pcap_lookupdev(errbuf);
 if(net_dev==NULL){
  printf("cannot get the network device info: %s\n",errbuf);
  return 1;
 } 

 if(pcap_lookupnet(net_dev,&netp,&maskp,errbuf)==-1){
  printf("cannot get the network device ip info:%s\n",errbuf);
  return 1;
 }

 sniffer_des=pcap_open_live(net_dev, 65535, 1, 1000, errbuf);
 if(sniffer_des==NULL){
  printf("cannot open the network device: %s\n",errbuf);
  return 1;
 }

 if(pcap_compile(sniffer_des, &fp, filter_exp, 0, maskp)==-1){
  printf("cannot compile the filter rule\n");
  return 1;
 }

 if(pcap_setfilter(sniffer_des,&fp)==-1){
  printf("cannot set the filter to the network device\n");
  return 1;
 }
 
 packet=pcap_next(sniffer_des,&hdr);
 if(packet==NULL){
  printf("cannot get the packet\n");
  return 1;
 }

 printf("Packet length: %d\n",hdr.len);
 printf("Sniffer time: %s\n",ctime((const time_t*)&hdr.ts.tv_sec));
 printf("length of portion present: %d\n",hdr.caplen);

 eth_header=(struct ether_header*)packet;
 if(ntohs(eth_header->ether_type)!=ETHERTYPE_IP){
  printf("not ethernet packet\n ");
  return 1;
 }

 ptr=eth_header->ether_dhost;
 int i;
 i=0;
 printf("destination address(MAC):");
 while(i<ETHER_ADDR_LEN){
  printf(" %x ",*ptr++);
  i++;
 }
 
 printf("\nsource address(MAC):");
 ptr=eth_header->ether_shost;
 i=0;
 while(i<ETHER_ADDR_LEN){
  printf(" %x ",*ptr++);
  i++;
 }

 printf("\n");
 return 0;
}
 

 

原创粉丝点击