最简单的抓包程序

#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <unistd.h>
#include <net/if.h>

int main(int argc, char **argv) {
  int sock, n, i;
  char buffer[2048];
  struct ethhdr *eth;
  struct iphdr *iph;
  struct ifreq ethreq;

  //创建原始套接字
  if((sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))<0) {
    perror("socket");
    exit(1);
  }


  /* 将网卡设为混杂模式,其中"eno16777736"为网络设备名称 */
  strncpy(ethreq.ifr_name,"eno16777736",IFNAMSIZ);
  if (ioctl(sock,SIOCGIFFLAGS,&ethreq)==-1) {
    perror("ioctl");
    close(sock);
    exit(1);
  }
  ethreq.ifr_flags|=IFF_PROMISC;
  if (ioctl(sock,SIOCSIFFLAGS,&ethreq<span id="transmark"></span>)==-1) {
    perror("ioctl");
    close(sock);
    exit(1);
  }

  /* 获取经过网络设备的所有数据包,并提取MAC的目的地址和源地址 */
  while(1) {
    printf("=========================================================================\n");

    i += n = recvfrom(sock, buffer, 2048, 0, NULL, NULL);
    printf("%d bytes read\n", n);

    eth = (struct ethhdr*)buffer;
    printf("Dest MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n", eth->h_dest[0], eth->h_dest[1], eth->h_dest[2], eth->h_dest[3]
, eth->h_dest[4],eth->h_dest[5]);
    printf("Source MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n",eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_sou
rce[3],eth->h_source[4],eth->h_source[5]);
  }
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值