2011-07-29 73 views
8

當我在我的Mac OS X上運行一個簡單的數據包嗅探器在C編碼,我根本沒有輸出,這是一件奇怪的事情!有人可以幫助我理解正在發生的事情嗎?Mac OS X上奇怪的RAW插槽

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

我編譯它在我的箱子運行它,沒有任何事情:

MacOsxBox:Desktop evariste$sudo ./simpleSniffer 

感謝您的幫助。

+0

對於此操作,使用libpcap可能會有更好的運氣,而不是直接嘗試打開原始套接字。 – duskwuff

回答

10

這不適用於* BSD(包括OSX/Darwin)。見調查here瞭解更多詳情:

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 

這個故事的寓意:使用libpcap這一點。它會讓你的生活更輕鬆。 (如果您使用MacPorts,請執行sudo port install libpcap。)

+0

感謝您的回答。對於我之前使用過的lpcap,它工作正常。我只是調查爲什麼這個簡單的原始套接字在Linux上,而不是在Mac OS X上,現在我得到了確認。謝謝。 – funnyCoder

0

我運行,並得到:

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

我猜這將是一些非常奇怪的,像你沒有權限打開一個套接字和標準錯誤重定向奇怪。

我建議的老式狼陷阱調試:

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"); 

...,看看它說。

+0

感謝查理,你在MacOsX或Linux上運行它(因爲在Linux上它沒問題)。它似乎在while循環中停止!我添加了舊的printf調試代碼(謝謝:-),只是:關於讀取套接字。奇怪的事情在這個mac箱子我有桌面上的所有權限。 – funnyCoder