2011年7月15日金曜日

イメージを描画する(11.2)

インターフェイスと bpf デバイスファイルのアタッチ

めも
///// bpf デバイスファイルのオープン /////
    NSArray *devices;
    NSString *deviceFile = @"/dev/bpf";
    int bpf;

    [deviceFile completePathIntoString:nil
                         caseSensitive:YES
                      matchesIntoArray:&devices
                           filterTypes:nil];
      
    for (NSString *device in devices) {
        bpf = open([device UTF8String],O_RDONLY,0);
        
        if (bpf != -1 ) {
            break;
        }
    }

// 使用するネットワークインターフェイスを用意する e.g "en0"
    struct ifreq ifr;
    bzero(ifr.ifr_name, sizeof(char) * IFNAMSIZ);
    strncpy(ifr.ifr_name, argv[1], IFNAMSIZ);

// デバイスファイルとネットワークインターフェイスを接続、設定する
    u_int isImmediately = 1;
    u_int isIO = 0;             // Input only;
    u_int bufferLength = (u_int)([[NSString stringWithCString:argv[2]
                                            encoding:NSUTF8StringEncoding] intValue]

    ioctl(bpf, BIOCSBLEN, &bufferLength); // 長さ
    ioctl(bpf, BIOCSETIF, &ifr);  // 接続
    ioctl(bpf, BIOCIMMEDIATE, &isImmediately); // すぐに書出す
    ioctl(bpf, BIOCSSEESENT, &isIO); // インプットのみ
あとは read(2) でデバイスファイルから読込む。
また読込みは bpf(4) Mac OS X Man page より bpf_hdr について。
The following structure is prepended to each packet returned by read(2):
"以下の構造体(bpf_hdr)はread(2) によって戻される各パケットの先頭に追加されます。"

Additionally, individual packets are padded so that each starts on a word boundary.  This requires that an application has some knowledge of how to get from packet to packet.  The macro BPF_WORDALIGN is defined in to facilitate this process.  It rounds up its argument to the nearest word aligned value (where a word is BPF_ALIGNMENT bytes wide).
p = (char *)p + BPF_WORDALIGN(p->bh_hdrlen + p->bh_caplen)

考え中。

// kernel -> bpf デバイスファイルへのデータコピーの状態
        struct bpf_stat status;
        ioctl(bpf, BIOCGSTATS,&status);
        NSLog(@"receive:%d, drop:%d",status.bs_recv, status.bs_drop);

bs_drop: パケットトラフィックがついていっていないとカーネルがドロップする。その数。

0 件のコメント:

コメントを投稿