从混杂的网络设备阅读 [英] Reading from a promiscuous network device

查看:182
本文介绍了从混杂的网络设备阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何从在C混杂(或嗅探)设备读取?我知道,你需要有root权限做到这一点,但我想知道是否有人知道哪些功能是必要的,做到这一点(普通​​插座也似乎没有意义在这里)?我想写的无线通信的实时分析工具。

Does anyone know how to read from a promiscuous (or sniffing) device in C? I know that you need to have root access to do it, but I was wondering if anyone knew what functions were necessary to do this (normal sockets wouldn't seem to make sense here)? I want to write a real-time analysis tool for wireless traffic.

推荐答案

在Linux下,你使用一个插座PF_PACKET读取原始设备,数据,如运行在混杂模式以太网接口:

On Linux you use a PF_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode:

s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))

这将收到发送到您的插座每个数据包的副本。这是很可能是你真的不希望每一个数据包,虽然。内核可以执行使用BPF的 Berkeley包过滤器过滤的第一级。 BPF本质上是一个基于堆栈的虚拟机:它处理一小部分,例如指令:

This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the Berkeley Packet Filter. BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as:

ldh = load halfword (from packet)  
jeq = jump if equal  
ret = return with exit code  

BPF的退出code告诉内核是否将数据包复制到插座或没有。它可以直接写相对小的BPF方案,使用的setsockopt(S,SOL_SOCKET,SO_ATTACH_FILTER,)。 (警告:内核需要一个结构sock_fprog,而不是一个结构bpf_program,不要混用那些或程序将无法在某些平台上工作)

BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, ). (WARNING: The kernel takes a struct sock_fprog, not a struct bpf_program, do not mix those up or your program will not work on some platforms).

有关事情相当复杂,你真的想使用libpcap的。 BPF是它可以做什么的限制,特别是在它可以每个分组执行的指令数。 libpcap的会照顾分割一个复合滤波器上的成两片,与内核执行滤波的第一级和更 - 能够用户空间code删除它实际上并没有想看的报文。

For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. libpcap will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see.

libpcap的也抽象内核接口您的应用程序code的。 Linux和BSD使用类似的API,但Solaris要求DLPI和Windows使用别的东西。

libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else.

这篇关于从混杂的网络设备阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆