Search code examples
c#datetimepacket-sniffers

Convert C# DateTime object to libpcap capture file timestamp


I am stuck in converting a DateTime object to a timestamp for the libpcap capture file format (is also used by wireshark, file format definitiom) in C#. The timestamp I can't manage to convert my object to is the Timestamp in the packet (record) header (guint32 ts_sec and guint32 ts_usec).


Solution

  • You can do it like so:

    DateTime dateToConvert = DateTime.Now;
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = date - origin;
    
    // Seconds since 1970
    uint ts_sec = Math.Floor(diff.TotalSeconds);
    // Microsecond offset
    uint ts_usec = 1000000 * (diff.TotalSeconds - ts_sec);