Boost logo

Boost Users :

Subject: Re: [Boost-users] [Asio] How do I dynamically select a port?
From: Etienne Philip Pretorius (icewolfhunter_at_[hidden])
Date: 2009-07-19 19:35:26


Robert Jones wrote:
> Hi All
>
> I'm new to Asio, and not a tcp/ip expert either, so if I'm approaching this
> all wrong
> then please tell me.
>
> I have two process on one machine, one of which streams a file to the other.
> In fact
> there may be several 'others', but one other will suffice to phrase the
> question.
>
> I need to dynamically select port numbers on which to stream the files to
> these other
> processes, based on whether that port number is available, and once the
> viability of
> using a particular port is established that port number can be communicated
> to the
> other process(es) by other means.
>
> So, the code sequence I have is this. At what point can I detect that use of
> this
> particular port number is ok? Is it appropriate to use
> from_string("127.0.0.1"), or
> should I use some other form for local sockets?
>
> Comments appreciated.
>
> using namespace boost;
> using asio :: ip :: tcp;
>
> unsigned short port = 2001;
>
> asio :: io_service io;
> tcp :: endpoint endpoint( asio :: ip :: address :: from_string( "127.0.0.1"
> ), port );
> tcp :: acceptor acceptor( io, endpoint );
> tcp :: iostream socket_stream;
> acceptor.accept( * socket_stream.rdbuf( ) );
>
> Thanks,
>
> - Rob.
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
TCP servers usually have a predefined port number to accept connections
from and the client that connects to the server gets allocated a client
side port number by the underlying (network) operating system.

So you will create an acceptor (first process) and then connect your
clients to it (other processes). Your connection details are unique when
factoring server_ip:port and client_ip:port combinations. You should set
the REUSE ADDRESS socket option on the server side so when restarting
your server you will not have to wait for the FIN_WAIT state to clear on
the last connected client before you can bind to the local socket
(acceptor) again.

You could use the examples in the asio section for the echo client and
server as a nice framework and just build your streaming code into it.

Your design considerations will need to look as
blocking/non-blocking/asio socket operations as all of them have their
advantages and disadvantages.

Best of luck,
Etienne


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