socket connect() vs bind()

后端 未结 6 795
臣服心动
臣服心动 2020-12-02 03:35

Both connect() and bind() system calls \'associate\' the socket file descriptor to an address (typically an ip/port combination). Their prototypes

6条回答
  •  天涯浪人
    2020-12-02 04:01

    Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind() set the source and connect() set the destination. Regardless of TCP or UDP.

    bind()

    bind() set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.

    If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).

    connect()

    • TCP has a "connected" state. connect() triggers the TCP code to try to establish a connection to the other side.
    • UDP has no "connected" state. connect() only set a default address to where packets are sent when no address is specified. When connect() is not used, sendto() or sendmsg() must be used containing the destination address.

    When connect() or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind() in Linux kernel source code.

    Side notes

    • listen() is TCP only.
    • In AF_INET family, the socket's source or destination address (struct sockaddr_in) is composed by an IP address (see IP header), and TCP or UDP port (see TCP and UDP header).

提交回复
热议问题