linux下sniffer程序的实现,C语言实现LINUX下网络嗅探程序SNIFFER

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc,char**argv){

int sock,n;

char buffer[2048];

unsigned char*iphead,*ethhead;

struct ifreq ethreq;int no=0;

//设置原始套接字方式为接收所有的数据包

if((sock=socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP)))<0){

perror("\n原始套接字建立失败\n");exit(1);}

//设置网卡工作方式为混杂模式,SIOCGIFFLAGS请求表示需要获取接口标志strncpy(ethreq.ifr_name,"eth0",IFNAMSIZ);//Interface Name size

if(ioctl(sock,SIOCGIFFLAGS,&ethreq)==-1){

perror("\n设置混杂工作模式失败\n");

close(sock);

exit(1);

}

//开始捕获数据并进行简单分析

while(1){

n=recvfrom(sock,buffer,2048,0,NULL,NULL);

no++;

printf("\n************%d packet%d bytes************\n",no,n);

//检查包是否包含了至少完整的以太帧(14),IP(20)和TCP/UDP(8)包头if(n<42){perror("recvfrom():");exit(0);}

ethhead=buffer;

printf("Dest MAC address:%02x:%02x:%02x:%02x:%02x:%02x\n",

ethhead[0],ethhead[1],ethhead[2],ethhead[3],ethhead[4],

ethhead[5]);

printf("Source MAC address:%02x:%02x:%02x:%02x:%02x:%02x\n",

ethhead[6],ethhead[7],ethhead[8],ethhead[9],ethhead[10],

ethhead[11]);

iphead=buffer+14;/*跳过Ethernet header*/

if(*iphead==0x45){/*Double check for IPv4*and no options present*/

printf("Source host:%d.%d.%d.%d,",

iphead[12],iphead[13],iphead[14],iphead[15]);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值