student96
student96

Reputation: 345

What is the best way to write a struct to file?

I have this two structs:

struct pcap_hdr_s {
    UInt32 magic_number;
    UInt16 version_major;
    UInt16 version_minor;
    int32_t thiszone;
    UInt32 sigfigs;
    UInt32 snaplen;
    UInt32 network;
};
//packet header
struct pcaprec_hdr_s {
    UInt32 ts_sec;
    UInt32 ts_usec;
    UInt32 incl_len;
    UInt32 orig_len;
};

which are initialised as follows(for example):

    let pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number: 0xa1b2c3d4,
                                            version_major: 2, 
                                            version_minor: 4, 
                                            thiszone: 0, 
                                            sigfigs: 0,
                                            snaplen: 
                                            pcap_record_size, 
                                            network: LINKTYPE_ETHERNET)

    let pcapRecHeader : pcaprec_hdr_s = pcaprec_hdr_s(ts_sec: UInt32(ts.tv_sec),
                                        ts_usec: UInt32(ts.tv_nsec), 
                                        incl_len: plen, 
                                        orig_len: length) 

I tried to create Data/NSData objects of the structs like this:

            //write pcap header
            let pcapHeaderData : NSData = NSData(bytes: pcapHeader, length: sizeofValue(pcapHeader))
            //write pcaprec header
            let pcapRecHeaderData : NSData = NSData(bytes: pcapRecHeader, length: sizeofValue(pcapRecHeader))

but I always get this error for each line:

"Connot convert value if type 'pcap_hdr_s' to expected arguemnt type 'UsafeRawPointer?'"

I had a look at the documentation of UnsafeRawPointers in Swift, but I don't get it enough as for now, to create the NSData object from the structs. Am I on the right way or is there a better one to accomplish my intend?

If this Data initialisation would work, my next steps would be

EDIT:

//packet ethernet header
struct ethernet_hdr_s {
    let dhost : [UInt8]
    let shost : [UInt8]
    let type : UInt16
};

let src_mac : [UInt8] = [0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB]
let dest_mac : [UInt8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55]

let ethernetHeader : ethernet_hdr_s = ethernet_hdr_s(dhost: dest_mac, shost: src_mac, type: 0x0800)

EDIT 2:

let payloadSize = packet.payload.count
            let plen = (payloadSize < Int(pcap_record_size) ? payloadSize : Int(pcap_record_size));

            bytesWritten = withUnsafePointer(to: &(packet.payload)) {
                $0.withMemoryRebound(to: UInt8.self, capacity: Int(plen)) {
                    ostream.write($0, maxLength: Int(plen))
                }
            }
            if bytesWritten != (Int(plen)) {
                // Could not write all bytes, report error ...
                NSLog("error in Writting packet payload, not all Bytes written: bytesWritten: %d|plen: %d", bytesWritten, Int(plen))
            }

Upvotes: 2

Views: 1057

Answers (2)

Martin R
Martin R

Reputation: 539815

You can write arbitrary data to an InputStream without creating a (NS)Data object first. The "challenge" is how to convert the pointer to the struct to an UInt8 pointer as expected by the write method:

let ostream = OutputStream(url: url, append: false)! // Add error checking here!
ostream.open()

var pcapHeader = pcap_hdr_s(...)
let headerSize = MemoryLayout.size(ofValue: pcapHeader)

let bytesWritten = withUnsafePointer(to: &pcapHeader) {
        $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        ostream.write($0, maxLength: headerSize)
    }
}
if bytesWritten != headerSize {
    // Could not write all bytes, report error ...
}

In the same way you can read data from in InputStream:

let istream = InputStream(url: url)! // Add error checking here!
istream.open()

let bytesRead = withUnsafeMutablePointer(to: &pcapHeader) {
    $0.withMemoryRebound(to: UInt8.self, capacity: headerSize) {
        istream.read($0, maxLength: headerSize)
    }
}
if bytesRead != headerSize {
    // Could not read all bytes, report error ...
}

If the file was possibly created on a different platform with a different byte order then you can check the "magic" and swap bytes if necessary (as described on https://wiki.wireshark.org/Development/LibpcapFileFormat):

switch pcapHeader.magic_number {
case 0xa1b2c3d4:
    break // Already in host byte order
case 0xd4c3b2a1:
    pcapHeader.version_major = pcapHeader.version_major.byteSwapped
    pcapHeader.version_minor = pcapHeader.version_minor.byteSwapped
    // ...
default:
    // Unknown magic, report error ...
}

To simplify the task of writing and reading structs one can define custom extension methods, e.g.

extension OutputStream {

    enum ValueWriteError: Error {
        case incompleteWrite
        case unknownError
    }

    func write<T>(value: T) throws {
        var value = value
        let size = MemoryLayout.size(ofValue: value)
        let bytesWritten = withUnsafePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                write($0, maxLength: size)
            }
        }
        if bytesWritten == -1 {
            throw streamError ?? ValueWriteError.unknownError
        } else if bytesWritten != size {
            throw ValueWriteError.incompleteWrite
        }
    }
} 

extension InputStream {

    enum ValueReadError: Error {
        case incompleteRead
        case unknownError
    }

    func read<T>(value: inout T) throws {
        let size = MemoryLayout.size(ofValue: value)
        let bytesRead = withUnsafeMutablePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: size) {
                read($0, maxLength: size)
            }
        }
        if bytesRead == -1 {
            throw streamError ?? ValueReadError.unknownError
        } else if bytesRead != size {
            throw ValueReadError.incompleteRead
        }
    }
}

Now you can write and read simply with

try ostream.write(value: pcapHeader)
try istream.read(value: &pcapHeader) 

Of course this works only with "self-contained" structs like your pcap_hdr_s and pcaprec_hdr_s.

Upvotes: 2

vadian
vadian

Reputation: 285072

You can convert pcap_hdr_s to Data and vice versa in Swift 3 with

  • pcap_hdr_s -> Data

    var pcapHeader : pcap_hdr_s = pcap_hdr_s(magic_number ...
    
    let data = withUnsafePointer(to: &pcapHeader) {
         Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: pcapHeader))
    }
    
  • Data -> pcap_hdr_s

    let header: pcap_hdr_s = data.withUnsafeBytes { $0.pointee }
    

Reference: round trip Swift number types to/from Data

Upvotes: 1

Related Questions