How can I convert a can data blf file to a pcap file

258 Views Asked by At

`How can I convert a can data blf file to a pcap file?

I need to convert all the packets present in this file to a pcap file. Here is an example of what I have tried, it has no errors but there is no result as well. have tried to open the blf file abd print the data but that has been a fail as well. I know that the blf file has data in it. `

import can
import dpkt
import datetime

blf_file_path = r'c:\Users\sahaanan\Desktop\blftopcap\NewSW_7209_Lines.blf' 
pcap_file_path = r'c:\Users\sahaanan\Desktop\blftopcap\output.pcap'    

# Open the BLF file for reading
with can.BLFReader(blf_file_path) as log:
    # Open the PCAP file for writing
    with open(pcap_file_path, "wb") as pcap_file:
        pcap_writer = dpkt.pcap.Writer(pcap_file)

        for entry in log:
            timestamp = entry.timestamp
            data = bytes(entry.data)

            # Print information about each entry
            print(f"Timestamp: {timestamp}, Data Length: {len(data)}")
    
            # Create a PCAP packet with timestamp
            pcap_packet = (timestamp, data)

            # Write the PCAP packet to the PCAP file
            pcap_writer.writepkt(pcap_packet)
            print("Conversion complete.")

the code runs without any errors but there is no output i have also tried using error handling with "try" and "exception" but the output is same.

1

There are 1 best solutions below

1
Tusher On BEST ANSWER

Here's a corrected version of your code:

import can
import dpkt
import datetime

blf_file_path = 'path_to_your_blf_file.blf'  
pcap_file_path = 'output.pcap' 

with can.BLFReader(blf_file_path) as log:
    # Open the PCAP file for writing
    with open(pcap_file_path, 'wb') as pcap_file:
        pcap_writer = dpkt.pcap.Writer(pcap_file)

        for entry in log:
            timestamp = entry.timestamp
            data = bytes(entry.data)

            # Calculate the timestamp in seconds and microseconds
            ts_sec = int(timestamp)
            ts_usec = int((timestamp - ts_sec) * 1e6)

           
            pcap_packet = (ts_sec, ts_usec, data)

        
            pcap_writer.writepkt(pcap_packet)
    
        print('Conversion complete.')

Make sure you have the necessary packages (can, dpkt) installed and that the paths to your input and output files are correct.