代码之家  ›  专栏  ›  技术社区  ›  Steve Folly

UUID和网络上的字节交换

  •  1
  • Steve Folly  · 技术社区  · 15 年前

    是否有一种标准的、可接受的方式来通过网络(或文件存储)传输字节交换UUID?(我希望发送/存储16个原始字节,而不是将UUID转换为字符串表示形式。)

    起初我认为应该将UUID划分为4个32位整数,并对每个整数调用htonl,但这听起来不太对劲。UUID具有内部结构(来自RFC 4122):

    typedef struct {
        unsigned32  time_low;
        unsigned16  time_mid;
        unsigned16  time_hi_and_version;
        unsigned8   clock_seq_hi_and_reserved;
        unsigned8   clock_seq_low;
        byte        node[6];
    } uuid_t;
    

    这样做是否正确:

    ...
    uuid.time_low = htonl( uuid.time_low );
    uuid.time_mid = htons( uuid.time_mid );
    uuid.time_hi_and_version = htons( uuid.time_high_and_version );
    /* other fields are represented as bytes and shouldn't be swapped */
    ....
    

    在写之前,然后相应的ntoh…在另一端阅读后调用?

    谢谢

    1 回复  |  直到 15 年前
        1
  •  3
  •   Jared Oberhaus    15 年前

    是的,这是正确的做法。

    每个数字( time_low , time_mid , time_hi_and_version )它们服从字节顺序。这个 node 字段不是。 clock_seq_hi_and_reserved clock_seq_low 也受字节顺序的约束,但它们都是一个字节,所以这无关紧要。

    当然,这取决于您是否在两端选择了正确的顺序,或者如果您无法控制,您是否了解另一端的顺序。当然,微软的UUID使用little endian。您可以看到Microsoft对UUID的定义 here .