tags:

views:

130

answers:

4

Based on this article I can get all incoming packets.

/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
    struct tm *ltime;
    char timestr[16];
    ip_header *ih;
    udp_header *uh;
    u_int ip_len;
    u_short sport,dport;
    time_t local_tv_sec;

    /* convert the timestamp to readable format */
    local_tv_sec = header->ts.tv_sec;
    ltime=localtime(&local_tv_sec);
    strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);

    /* print timestamp and length of the packet */
    printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);

    /* retireve the position of the ip header */
    ih = (ip_header *) (pkt_data +
        14); //length of ethernet header

    /* retireve the position of the udp header */
    ip_len = (ih->ver_ihl & 0xf) * 4;
    uh = (udp_header *) ((u_char*)ih + ip_len);

    /* convert from network byte order to host byte order */
    sport = ntohs( uh->sport );
    dport = ntohs( uh->dport );

    /* print ip addresses and udp ports */
    printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
        ih->saddr.byte1,
        ih->saddr.byte2,
        ih->saddr.byte3,
        ih->saddr.byte4,
        sport,
        ih->daddr.byte1,
        ih->daddr.byte2,
        ih->daddr.byte3,
        ih->daddr.byte4,
        dport);
}

But how do I extract URI information in packet_handler?

A: 

Not every packet has a URI.

In an http request, the URI will be transmitted very near the beginning of the connection, but subsequent packets are just pieces of the larger request.

To find the URI (and all data) being requested, look in the pkt_data.

abelenky
@abelenky,Can you elaborate how to look in the `pkt_data`?
Gtker
The type of pkt_data is "const u_char *". I must assume you know how to examine an array of unsigned characters. If nothing else, try printf.
abelenky
Tried,not there...
Gtker
+1  A: 

You're not following the best example. The URL you posted is an example that handles UDP packets but HTTP is based on TCP.

R Samuel Klatchko
Do you find a better example?
Gtker
As @klatchko points out, this code handles UDP packets, and won't easily pick up HTTP, which is carried over TCP.
abelenky
A: 

Usually (ignoring Connection: keep-alive, very short first packet etc.) the URI would be the second word on the first line of the first outgoing TCP packet (defining words as space delimited, lines as CR LF delimited).

As wireshark is based on libpcap, is open source and does a pretty good job of this, you can start from looking there.

Ofir
A: 

See my answer here.

brickner