
// Create the session object.
gnutls_session_t session;
ret = gnutls_init(&session, GNUTLS_CLIENT);
if (ret != GNUTLS_E_SUCCESS) {
  fprintf(stderr, "error: gnutls_init: %s\n",
	    gnutls_strerror(ret));
  exit(1);
}

// Configure the cipher preferences.
const char *errptr = NULL;
ret = gnutls_priority_set_direct(session, "NORMAL", &errptr);
if (ret != GNUTLS_E_SUCCESS) {
  fprintf(stderr, "error: gnutls_priority_set_direct: %s\n"
	    "error: at: \"%s\"\n", gnutls_strerror(ret), errptr);
  exit(1);
}

// Install the trusted certificates.
ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cred);
if (ret != GNUTLS_E_SUCCESS) {
  fprintf(stderr, "error: gnutls_credentials_set: %s\n",
	    gnutls_strerror(ret));
  exit(1);
}

// Associate the socket with the session object and set the server
// name.
gnutls_transport_set_int(session, sockfd);
ret = gnutls_server_name_set(session, GNUTLS_NAME_DNS,
			       host, strlen(host));
if (ret != GNUTLS_E_SUCCESS) {
  fprintf(stderr, "error: gnutls_server_name_set: %s\n",
	    gnutls_strerror(ret));
  exit(1);
}

// Establish the session.
ret = gnutls_handshake(session);
if (ret != GNUTLS_E_SUCCESS) {
  fprintf(stderr, "error: gnutls_handshake: %s\n",
	    gnutls_strerror(ret));
  exit(1);
}

