Mac OS X上的奇怪RAW套接字

fun*_*der 10 c sockets macos sniffing packet-sniffers

当我在Mac OS X上运行一个用C编码的简单数据包嗅探器时,我根本没有输出,这是一个奇怪的事情!有人可以帮我理解发生了什么.

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

int main(void) {
   int i, recv_length, sockfd;

   u_char buffer[9000];

   if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) {
        printf("Socket failed!!\n");

        return -1;
   }

   for(i=0; i < 3; i++) {
      recv_length = recv(sockfd, buffer, 8000, 0);
      printf("Got some bytes : %d\n", recv_length);
   }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我编译它并在我的盒子上运行它没有任何进展:

MacOsxBox:Desktop evariste$sudo ./simpleSniffer
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

mpo*_*llo 12

这不适用于*BSD(包括OSX/Darwin).有关详细信息,请参阅此处的调查:

b. FreeBSD
**********

FreeBSD takes another approach. It *never* passes TCP or UDP packets to raw
sockets. Such packets need to be read directly at the datalink layer by using
libraries like libpcap or the bpf API. It also *never* passes any fragmented 
datagram. Each datagram has to be completeley reassembled before it is passed
to a raw socket.
FreeBSD passes to a raw socket:
    a) every IP datagram with a protocol field that is not registered in
    the kernel
    b) all IGMP packets after kernel finishes processing them
    c) all ICMP packets (except echo request, timestamp request and address
    mask request) after kernel finishes processes them
Run Code Online (Sandbox Code Playgroud)

故事的道德:libpcap用于此.它会让你的生活更轻松.(如果您使用MacPorts,请执行sudo port install libpcap.)

  • 为什么使用 libpcap 是道德的?有一些很好的例子(如果你继续挖掘,你至少会发现一些)解释如何使用伯克利数据包过滤器等:[vankuik.nl](https://www.vankuik.nl/ 2012-02-09_Writing_ethernet_packets_on_OS_X_and_BSD) [bastion.rieck.ru](http://bastian.rieck.ru/blog/posts/2009/bpf/) 实际上,我更喜欢使用 BPF 而不是 libpcap。您无需学习 API;相反,您可以照常进行。 (2认同)