Sockets - Using INADDR_ANY on client side

前端 未结 4 1799
长情又很酷
长情又很酷 2020-12-09 13:38

I recently ran into this blog post which describes a TCP server client using libev. The sever uses INADDR_ANY to bind to an interface which is something I\'m fa

相关标签:
4条回答
  • 2020-12-09 14:14

    There is an old BSD convention that connecting to INADDR_ANY means you want to connect to the loopback network. The linux network code explicitly supports this (search for INADDR_ANY in this file). I have no idea what other OSes do or don't support it.

    0 讨论(0)
  • 2020-12-09 14:18

    At client side, using INADDR_ANY is redundant, but I have seen some code with that, I guess it is for 'completeness'. You can specify the interface at client side if you want to force a specific interface, e.g. in multihomed machines.

    Binding to a port at client side is uncommon as well. It is normally a better idea to let the system to find an available port, or else the program may fail because the port happens to be in use by a client or by a server.

    0 讨论(0)
  • 2020-12-09 14:25

    This is the answer as provided by nos in a comment. If nos comes back and posts it as an answer, I will mark nos' post as the answer and delete this one.

    INADDR_ANY is normally defined as 0. That is the IP address 0.0.0.0. RFC 1122 says that means "This host on this network". The linux IP stack seems to just route this to the loopback interface. (e.g. try ping 0.0.0.0 or even just ping 0). I'd say the author made a typo, and should have used INADDR_LOOPBACK.

    0 讨论(0)
  • 2020-12-09 14:31

    It seems like your question is not really about "client-side", but about bind vs connect.

    INADDR_ANY can be sensibly used with bind on both client and server. Using it with connect() is pointless and should cause a connection failure.

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