struct sockaddr_in member byte order for bind()

前端 未结 2 1896
耶瑟儿~
耶瑟儿~ 2021-01-28 05:02

I\'m learning socket programming and am confused by what I feel is inconsistent use of htons() and family of functions in my learning material. I\'m currently readi

2条回答
  •  难免孤独
    2021-01-28 05:45

    Why is ntohs() used on adr_inet.sin_port in the first instance, but htons() in the second?

    The first is a mistake, but in practice works anyway.

    Nowadays practically all machines use 8-bit bytes and either consistent big-endian or consistent little-endian formats. On the former both hton[sl] and ntoh[sl] are no-ops; on the latter both reverse the byte order, and thus actually do the same thing even though their intended semantics are different. Thus using the wrong one still works on all systems you're likely to run a program on.

    Back when the socket API was designed this wasn't always the case; for example the then-popular PDP-11 somewhat infamously used 'middle-endian' (!) aka 'NUXI' order for 32-bit.

    Why is neither ntohs() nor htons() used on adr_inet.sin_family?

    Again in ancient times the Internet Protocol stack was only one of several (up to a dozen or so) competing network technologies. The family field distinguishes different types of sockaddr_* structures for these different protocols, which did not all follow the Internet 'rule' for big-endian, at least not consistently. As there was no universal network representation for family they just left it in host order -- which is usually more convenient for host software.

    Nowadays in practice nobody uses any families but INET, INET6, and sometimes UNIX -- and the latter can be replaced by using named pipes in the filesystem which is usually at least as good.

提交回复
热议问题