Jibbity jobby
Jibbity jobby

Reputation: 1325

Port specification on an asio tcp client application

I'm rewriting a python twisted server in C++ using asio. I have set up the following examples from

http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/tutorial.html:

Daytime.1 - A synchronous TCP daytime client
Daytime.3 - An asynchronous TCP daytime server

and they seem to be functioning correctly. However, what is puzzling me is that when I created the twisted server both it and the client side required explicit specification of the IP addresses and port numbers. I am having a slightly different experience here:

  1. On the client application no specification of the port number is required. I can successfully connect to the server by using only 127.0.0.1 as a command line argument.
  2. Also, I appear to be able to connect to the same server with any legal variant of this IP address, as long as the first byte is 127 (eg 127.1.2.3 connects).
  3. There's a literal in the client code specifying to connect using what I assume is an OS provided "daytime" TCP service. However, there is no reference to this in the server code. Why do I have to specify a particular service to connect to? I also suspect that this service could be related to the behaviour in points 1 and 2.

Now I know that the server has an acceptor socket listening that only establishes the connection once it receives a request but I would like some more details here.

Upvotes: 0

Views: 192

Answers (1)

Arunmu
Arunmu

Reputation: 6901

Daytime is well known service in *nix world. You can get the list of known service by looking at /etc/services file and you can see below records in it:

daytime          13/udp     # Daytime (RFC 867)
daytime          13/tcp     # Daytime (RFC 867)

When service_name is provided with the host name, the tcp endpoint uses below version of getaddrinfo:

int error = ::getaddrinfo(host, service, &hints, result);   

Looking at the man page [Emphasis mine]:

int
getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res)

The hostname and servname arguments are either pointers to NUL-terminated strings or the null pointer.  An acceptable
     value for hostname is either a valid host name or a numeric host address string consisting of a dotted decimal IPv4
     address or an IPv6 address.  The servname is either a decimal port number or a *service name listed in services(5)*.  At
     least one of hostname and servname must be non-null.

So, in short, provided the correct service name, it knows the correct port number to use. 13 in case of "daytime" service.

Upvotes: 1

Related Questions