Boost logo

Boost Users :

Subject: Re: [Boost-users] Enhancing the boost::asio::connect() socket interface
From: Maarten de Vries (maarten_at_[hidden])
Date: 2017-09-24 19:02:16


On 24 September 2017 at 19:37, Vinnie Falco via Boost-users <
boost-users_at_[hidden]> wrote:

> >On Sun, Sep 24, 2017 at 1:15 AM, martin doc via Boost-users <
> boost-users_at_[hidden]> wrote:
> > As boost::asio::connect() closes an open socket passed to it before
> making
> > the remote connection, it's not possible to pass connect() a prebaked
> > socket.
>
> What makes you think that? My reading of the implementation is that
> the socket is only closed when:
>
> 1. The range of addresses passed to connect() has more than one element,
> and
> 2. The connection attempt for the first address fails.
>
> See:
>
> <https://github.com/boostorg/asio/blob/b002097359f246b7b1478775251dfb
> 153ab3ff4b/include/boost/asio/impl/connect.hpp#L108
>
> You can avoid the socket closure by only attempting to connect to one
> address.
>

​Judging from that code, the socket is always closed before attempting a
connect. The `s.close()`​ is right above the `s.connect()`.

My guess is this is because the iterated endpoints may be using different
protocols (TCP/IPv4 or TCP/IPv6 for example). Things become a bit hairy
when you take that into account. You can't use a local TCP/IPv4 endpoint
and connect to a TCP/IPv6 peer. What should `asio::connect` do in that
case? Ignore the IPv6 endpoint? Or just not bind to a specific local
endpoint? Or should you give it an iterator with at least one local
endpoint per protocol in the iterated remote endpoints? And in that case,
what should `asio::connect` do if there isn't a matching local endpoint?
Return an error? Or not bind to a local endpoint? Personally I'm not sure
which behaviour makes the most sense here. It seems like ASIO decided to
sidestep the whole issue.

You can still use `socket.connect()` directly with a single endpoint.
Alternatively, you can wrap an already connected socket by passing the file
descriptor to asio:

http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/basic_stream_socket/basic_stream_socket/overload4.html
http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/basic_stream_socket/assign.html
​
Another option is to write your own `connect` function that does support
binding to a local endpoint. If you have a nice way of dealing with
different protocols in the iterated remote endpoints, you could even
suggest your function for inclusion in ASIO.

--
​ Maarten​


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net