Search code examples
csocketsrtppackets

In C, How can i store received rtp packets into .pcap file - UDP


i need to store rtp packets that are received using recvfrom() into .pcap file.

I tried to open a file with the extension of .pcap and done direct fwrite whatever i received (ie void *buf), but when i tried to open that file using wireshark it given error statement as "not understandable" What i'm supposed to do to make it as understandable??

Code i used:

recvfrom(sockfd, buf, len, flags, (struct sockaddr *)&src_addr->ss, &src_addr->len);
fp=fopen("test.pcap","a+");
fprintf(fp, "%s",buf);

In UDP connection how can i receive and store rtp packets into understandable .pcap file? Is there anything extra need to be added with the received rtp pcakets?


Solution

  • You have to add the below headers in order to write the packets as pcap file.

    Global Header

    This header starts the libpcap file and will be followed by the first packet header:
    
       typedef struct pcap_hdr_s {
                guint32 magic_number;   /* magic number */
                guint16 version_major;  /* major version number */
                guint16 version_minor;  /* minor version number */
                gint32  thiszone;       /* GMT to local correction */
                guint32 sigfigs;        /* accuracy of timestamps */
                guint32 snaplen;        /* max length of captured packets, in octets */
                guint32 network;        /* data link type */
        } pcap_hdr_t;
    

    Record (Packet) Header :

    Each captured packet starts with (any byte alignment possible):
    
    typedef struct pcaprec_hdr_s {
            guint32 ts_sec;         /* timestamp seconds */
            guint32 ts_usec;        /* timestamp microseconds */
            guint32 incl_len;       /* number of octets of packet saved in file */
            guint32 orig_len;       /* actual length of packet */
    } pcaprec_hdr_t;
    

    Check the link for explanation of Headers.

    Check this link for sample snippet of code.