2011年7月29日金曜日

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

bpf のフィルタを設定したい。そこで bpf(4) を見ます。オペコード、アキュームレータ、インデックスレジスタ... アセンブリ言語?疑似マシンへの命令は僕には難しすぎます。そんな僕のために libpcap は疑似マシン命令を手軽にコンパイルしてくれるということなので頼ります。

/*事前に/dev/bpf* はオープンされていて、ネットワークインターフェイス(struct ifreq ifr)がアタッチされている。*/

    char errorBuffer[PCAP_ERRBUF_SIZE];
    bpf_u_int32 mask;
    bpf_u_int32 net;

    if ((pcap_lookupnet(ifr.ifr_name, &net, &mask, errorBuffer)) == -1 ) {
        fprintf(stderr,"pcap_lookupnet:%s",errorBuffer);
        net = 0;
        mask = 0;
    }

    u_int dataLinkType;
    u_int bufferLength;

    ioctl(bpf, BIOCGDLT, &dataLinkType);
    ioctl(bpf, BIOCGBLEN, &bufferLength);

    pcap_t *tmpHandle = pcap_open_dead(dataLinkType, bufferLength);

    if (!tmpHandle) {
        fprintf(stderr,"pcap_open_dead:NULL");
    }

    struct bpf_program *bpfProgram = (struct bpf_program *)malloc(sizeof(struct bpf_program));
    const char *filterExpression = "ether proto \\ip";
    int optimize = 0;

    if (pcap_compile(tmpHandle,
                     bpfProgram,
                     filterExpression,
                     optimize,
                     mask) == -1 ) {
        fprintf(stderr,"pcap_compile:%s",pcap_geterr(tmpHandle));
    }

    pcap_close(tmpHandle);
    
    ioctl(bpf, BIOCSETF, bpfProgram);
    
    pcap_freecode(bpfProgram);

0 件のコメント:

コメントを投稿