Practice Exercise #11

Write a C++ program that accepts three command line arguments:

  • the hostname of a server
  • the port number of that server
  • the name of a local file

The program should connect (via TCP) to the server on the supplied hostname and port. Once connected, the program should read the bytes in from the local file, and it should write those bytes over the TCP connection. Once all of the bytes have been written, the program should close the TCP connection and exit.

To test your program, you can run a server using the "nc" program. For example, to run the server on port 5555, and to have the server redirect the incoming bytes to file "output.bin", run the following command:

nc -l 5555 > output.bin

Note that nc will exit once it has processed a single connection, so you'll need to rerun nc each time you test your client.

There are a few requirements on your code:

  • you should modularize it nicely; consider splitting it into multiple source files, for example by isolating all of the network-specific code in a module.

  • you should use read/write both to read from the input file and write over the socket to the server; note this means you need to pay attention to the possibility that read/write might return EINTR, and they might read/write less than you ask for. I recommend writing some utility functions to deal with this.