网络编程里用到的函数

Author Avatar
Aryb1n 5月 05, 2018

htons — host 2 network order, 2字节
htonl — host 2 network order, 4字节

ntohs — network 2 host order, 2字节
ntohl — network 2 host order, 4字节

在我的环境(Ubuntu 16.04 64bit)里

// -m32
unsigned short 2
unsigned int   4
unsigned long  4

// 64 bit
unsigned short 2
unsigned int   4
unsigned long  8

所以我在别人的项目里看到这样的代码…是没有问题的吗…?

char* encode32(char* buf, uint32_t data) {
    uint32_t ndata = htonl(data);
    memcpy(buf, (void*)(&ndata), sizeof(uint32_t));

    return buf + sizeof(uint32_t);
}

htonl的参数是4字节..而在我的环境下long是8字节 ==!
试了一下, 是影响结果的…那么

喔. 查阅了一下, 应该是说这个函数定义就是接受4字节的uint32_t参数, 返回4字节…
只不过这个名字…emmmmmm

后来

https://stackoverflow.com/questions/3022552/is-there-any-standard-htonl-like-function-for-64-bits-integers-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
https://stackoverflow.com/questions/809902/64-bit-ntohl-in-c