Does sin_addr.s_addr = INADDR_ANY; need htonl at all?

前端 未结 7 1781
一整个雨季
一整个雨季 2020-12-06 03:56

I came across two threads:

Socket with recv-timeout: What is wrong with this code?

Reading / Writing to a socket using a FILE stream in c

one uses

7条回答
  •  执笔经年
    2020-12-06 04:24

    INADDR_ANY is the "any address" in IPV4. That address is 0.0.0.0 in dotted notation, so 0x000000 in hex on any endianness. Passing it through htonl has no effect.

    Now if you want to wonder about other macro constants, look at INADDR_LOOPBACK if it's defined on your platform. Chances are it will be a macro like this:

    #define INADDR_LOOPBACK     0x7f000001  /* 127.0.0.1   */
    

    (from linux/in.h, equivalent definition in winsock.h).

    So for INADDR_LOOPBACK, an htonl is necessary.

    For consistency, it could thus be better to use htonl in all cases.

提交回复
热议问题