Search code examples
c++socketsboost

boost socket vs stream_socket endpoint in ctor vs connect method


There is boost::basic_socket and boost::basic_stream_socket; both have constructor that accepts const endpoint_type & endpoint and documentation says

An endpoint on the local machine to which the stream socket will be bound.

yet there is a connect method, where the doc says

peer_endpoint -- The remote endpoint to which the socket will be connected.

How does it work, what's what? When I'm writing a client, I'd create a socket, not providing endpoint in ctor, then call connect and then do read/write. And when writing a server, I'd use the ctor endpoint and not be calling connect? And what's the difference between normal socket and stream socket?


Solution

  • In the ctor the endpoint is to be used with bind() which binds the socket to a an address and a port in the local machine

    In connect the endpoint represents the remote address and port you are connection to

    In general any socket needs to be bound before using it with accept() or connect() or any send/recv method . But when you use connect() syscall the system checks if the socket is already bound and if not it binds it for you so it's better when using socket as a client to connect to server to let the os bind the socket for you, there is an exception which is ConnectEx on windows as it doesn't bind the socket automatically so you are responsible to bind it yourself.

    For servers the things are different because you bind the acceptor socket to the local address and port clients are connecting to so the os can't deduce which address or port you wish to receive connections on in order to bind the socket for you , as a result you have to explicitly call bind() with the your chosen address and port