Darth-L
Darth-L

Reputation: 23

libpcap on iOS ,the pcap_next() always return null

I am a beginner of iOS and my design of graduation is to develope a app that can capture packets on iOS.

I use the libpcap library .My iPhone is JB and I can already run app as root. More specificly,I can get my net_interface :en0,but I can't capture any packet.The pcap_next() always return null.

this is my code :

-(IBAction)capture:(id)sender{
    char error_content[PCAP_ERRBUF_SIZE];
    char *net_interface=NULL;
    net_interface=pcap_lookupdev(error_content);
    NSString *devstr = [[NSString alloc] initWithUTF8String:net_interface];
    text1.text=devstr;

    pcap_t *pcap_handle;
    pcap_handle = pcap_open_live(net_interface, BUFSIZ, 0, 2, error_content);

    struct pcap_pkthdr packet_capture;
    const u_char *packet_flag;
    packet_flag= pcap_next(pcap_handle, &packet_capture);
    if (!packet_flag) {
        text2.text=@"capture failed";
    }
    else{
       NSString *length =[[NSString alloc]initWithFormat:@"the length of packet is         %d",packet_capture.len];
       text2.text=length;
       [length release];
    }
       pcap_close(pcap_handle);
    }
@end

If someone have the similar exp about it or know how to solve it,I would be much grateful if you can contact me via [email protected] .

Upvotes: 2

Views: 1738

Answers (1)

user862787
user862787

Reputation:

packet_flag= pcap_next(pcap_handle, &packet_capture);
if (!packet_flag) {
    text2.text=@"capture failed";
}

To quote the pcap_next() man page:

pcap_next() returns a pointer to the packet data on success, and returns NULL if an error occured, or if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a read timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read), or if no more packets are available in a ``savefile.'' Unfortunately, there is no way to determine whether an error occured or not.

iOS, like OS X, is built atop a 4.4-Lite-derived OS, and uses BPF; BPF is a packet that supports a read timeout that starts before any packets arrive and, given that you specified 2 as the timeout argument to pcap_open_live(), the timeout is 2 milliseconds, so, if no packet arrives within 2 milliseconds after you call pcap_next(), pcap_next() will return NULL.

You made the right choice by using pcap_loop(). pcap_next() is not a very good API; pcap_next_ex() is better, as are pcap_dispatch() and pcap_loop().

Upvotes: 1

Related Questions