Strange RAW Socket on Mac OS X

When I run a simple packet sniffer encoded in C on my Mac OS X, I didn’t get anything at all, this is a strange thing! can someone help me understand what is happening.

#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; } 

I compile it and run on my box, and nothing happens:

 MacOsxBox:Desktop evariste$sudo ./simpleSniffer 

Thank you for your help.

+8
c sockets macos packet-sniffers sniffing
source share
2 answers

This will not work on * BSD (including OSX / Darwin). See the study here for more details.

 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 

The moral of the story: use libpcap for this. It will make your life a lot easier. (If you are using MacPorts, do sudo port install libpcap .)

+10
source share

I run it and get:

 # ./a.out Got some bytes : 176 Got some bytes : 168 Got some bytes : 168 # 

I assume that it will be something really strange, for example, you do not have permission to open the socket, and stderr is redirected strangely.

I would suggest a good old-fashioned debugged wolf trap:

  printf("I got ti 1\n"); if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) { printf("Socket failed!!\n"); return -1; } printf("I got to 2\n"); for(i=0; i < 3; i++) { printf("About to read socket.\n"); recv_length = recv(sockfd, buffer, 8000, 0); printf("Got some bytes : %d\n", recv_length); } printf("Past the for loop.\n"); 

... and see what he says.

0
source share

All Articles