免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2315 | 回复: 2
打印 上一主题 下一主题

libpcap程序,获取源IP与目的IP完全相同,请高手给看看,谢谢 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-05-24 15:31 |只看该作者 |倒序浏览
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pcap.h>
#include<string.h>
#include<time.h>
#include<error.h>
struct ether_header
{
unsigned char source[6];
unsigned char dest[6];
unsigned int type;
};
struct ip_header
{
#ifdef WORDS_BIGENDIAN
u_int8_t ip_version:4,
  ip_header_length:4;
#else
u_int8_t ip_header_length:4,
   ip_version:4;
#endif
u_int8_t ip_tos;   /*type of service */
u_int16_t ip_length;    /*length */
u_int16_t ip_id; /*identity */
u_int16_t ip_off; /* offset */
u_int8_t ip_ttl; /*time to live*/
u_int8_t ip_protocol; /* type of protocol*/
u_int16_t ip_chechsum;  /* chechsum */
struct in_addr source;
struct in_addr dest;
};
void packet_callback(unsigned char* argument,const struct pcap_pkthdr* packet_header, const unsigned char* packet_content)
{
struct ether_header* eptr;
struct ip_header* iptr;
eptr=(struct ether_header*) packet_content;
switch(ntohs(eptr->type))
{
  case 0x0800 :/*IP*/
    iptr=(struct ip_header*)(packet_content+14);
    switch(iptr->ip_protocol)
    {
    case 6: /* TCP */
     printf("%s %s \n", inet_ntoa(iptr->source),inet_ntoa(iptr->dest));
     break;
   }
    break;
}
return ;
};
int main(int argc ,char* argv[])
{
char errbuf[PCAP_ERRBUF_SIZE]; //store the information for error
char* net_interface; //store the chars of net interface
bpf_u_int32 ipaddr;
bpf_u_int32 ipmask;
pcap_t* pcap_handle; //the handle of pcap
struct bpf_program bpf_filter;
char bpf_filter_string[]="tcp"; //the filter string

net_interface=pcap_lookupdev(errbuf);
pcap_lookupnet(net_interface,&(ipaddr),&(ipmask),errbuf);
pcap_handle=pcap_open_live(net_interface,BUFSIZ,1,0,errbuf);
if(pcap_handle==NULL)
{
  printf("Error in function pcap_open_live. Exiting ...\n");
  exit(1);
}
if(pcap_compile(pcap_handle,&bpf_filter,bpf_filter_string,0,ipaddr)==-1)
{
  printf("Error in function pcap_compile. Exiting ...\n");
  exit(1);
}
if(pcap_setfilter(pcap_handle,&bpf_filter)==-1)
{
  printf("Error in function pcap_setfilter. Exiting ...\n");
  exit(1);
}
pcap_loop(pcap_handle,-1,packet_callback,NULL);
pcap_close(pcap_handle);
return 0;
}

论坛徽章:
0
2 [报告]
发表于 2007-05-25 14:08 |只看该作者
inet_ntoa的返回结果是放在全局变量里面的,这样一条一句里面printf 2个inet_ntoa的结果,都只会打印出最后进行计算的那个

论坛徽章:
0
3 [报告]
发表于 2007-05-25 14:13 |只看该作者
执行顺序中是先计算 inet_ntoa(iptr->dest), 假设返回结果保存在全局变量A里面,后面计算inet_ntoa(iptr->source)的时候结果也是保存在变量A里面,然后再是printf,打印的都是A里面的值,所以显示结果是一样
PS:是先计算inet_ntoa(iptr->source)还是inet_ntoa(iptr->dest)我也记不大清楚了,LZ自己看看吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP