#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

static void die() { perror(NULL); exit(1); }

int main()
{
  int sfd = 0, errcode = 0;
  struct addrinfo hints;
  struct addrinfo *addresses = NULL, *ap = NULL;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  if ((errcode = getaddrinfo("cproxy", "3128", &hints, &addresses)) != 0) {
  /* if ((errcode = getaddrinfo("slashdot.org", "80", &hints, &addresses)) != 0) { */
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(errcode));
    die();
  }

  ap = addresses; // the tail of list is ignored

  if ((sfd = socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol))
      == -1)
    die();

  {
#ifdef LINGER_AS_INT
    const int x = 5; // ==> `Invalid argument'
#else
    struct linger x = { 1, 5 }; /* `close' should block until data are
				 * transmitted or timeout (5 seconds)
				 * has expired. */
#endif
    if (setsockopt(sfd, SOL_SOCKET, SO_LINGER, &x, sizeof(x)) == -1) {
      perror("setsockopt");
      close(sfd);
      exit(1);
    }
  }

  if (connect(sfd, ap->ai_addr, ap->ai_addrlen) == -1)
    die();

  freeaddrinfo(addresses);
  addresses = ap = NULL;

  close(sfd);
  return 0;
}
