2.2 Establishing a TCP Connection

Let’s observe a network connection at work. Type in the following program and watch the output. Within a second, it connects via TCP (/inet/tcp) to a remote server and asks the service ‘daytime’ on the machine what time it is:

BEGIN {
  daytime_server     = "time-a-g.nist.gov"
  daytime_connection = "/inet/tcp/0/" daytime_server "/daytime"
  daytime_connection |& getline
  print $0
  daytime_connection |& getline
  print $0
  close(daytime_connection)
}

Even experienced awk users will find the fourth and sixth line strange in two respects:

The ‘|&’ operator was introduced in gawk 3.1 in order to overcome the crucial restriction that access to files and pipes in awk is always unidirectional. It was formerly impossible to use both access modes on the same file or pipe. Instead of changing the whole concept of file access, the ‘|&’ operator behaves exactly like the usual pipe operator except for two additions:

In the earlier example, the ‘|&’ operator tells getline to read a line from the special file /inet/tcp/0/time-a-g.nist.gov/daytime. We could also have printed a line into the special file. But instead we just consumed an empty leading line, printed it, then read a line with the time, printed that, and closed the connection. (While we could just let gawk close the connection by finishing the program, in this web page we are pedantic and always explicitly close the connections.)

Network services like daytime are not really useful because there are so many better ways to print the current time. In the early days of TCP networking, such a service may have looked like a good idea for testing purposes. Later, simple TCP services like these have been used to teach TCP/IP networking and therefore you can still find much educational material of good quality on the Internet about such outdated services. The list of servers that still support the legacy service daytime can be found at Wikipedia. We hesitated to use this service in this manual because it is hard to find servers that still support services like daytime openly to the Internet. Later on we will see that some of these nostalgic protocols have turned into security risks.