Search code examples
objective-cnetwork-programmingpackets

What is the canonical way to create network packets in Objective C?


Coming from python I could do something like this.

values = (1, 'ab', 2.7)
s = struct.Struct('I 2s f')
packet = s.pack(*values)

I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C?


Solution

  • Using a C struct is the normal approach. For example:

    typedef struct {
        int a;
        char foo[2];
        float b;
    } MyPacket;
    

    Would define a type for an int, 2 characters and a float. You can then interpret those bytes as a byte array for writing:

    MyPacket p = {.a = 2, .b = 2.7};
    p.foo[0] = 'a'; 
    p.foo[1] = 'b';
    
    char *toWrite = (char *)&p; // a buffer of size sizeof(p)