Endianness and Socket Programming in C

后端 未结 1 615
暖寄归人
暖寄归人 2021-02-09 01:53

I\'m making a program that communicate with certain patient monitor using C sockets. I\'m using connection-less sockets (UDP) to communicate with the device. But there is endian

相关标签:
1条回答
  • 2021-02-09 02:20

    First of all, since a is apointer, your code should at minimum do this...

    b.v1 = ntohs(a->v1);
    b.v2 = ntohl(a->v2);
    

    Second of all, the answer depends on circumstances and specification of the patient monitor. Who writes the code for the patient monitor? Is there a specification for it? What machine architecture is it using(in case you know), are you dealing with just one model or are there many versions of the monitor -- can you change the monitor, etc. etc.

    Im going to assume that you cannot change the monitor, and that the byte order is documented somewhere -- and you may have to create your own unpack/pack routines, by doing byte addressing and bit manipulation -- that is unless you know that the format exactly matches that of "network" order -- and that padding of structs are the same in the network buffer.

    So something like;

    void unpack(struct *b, unsigned char *buffer)
    {
       b->v1 = (buffer[0] <<8)|(buffer[1]);   
       b->v2 = (buffer[2] <<24)|(buffer[3] <<16)|(buffer[4] <<8)|(buffer[5]);
       etc....
    }   
    

    or like this if you prefer to you ntohX;

    void unpack(struct *b, unsigned char *buffer)
    {
       b->v1 = ntohs(buffer+0);   
       b->v2 = ntohl(buffer+2);
       etc....
    }   
    

    However if you do control the monitor code, then using a tool like protocol buffers would get rid of all the complexity of doing bit manipulation and worry about byte orders....

    0 讨论(0)
提交回复
热议问题