documented update
[gnutls.git] / doc / examples / ex-cxx.cpp
blobc675f60fcfc4b683340effd0bc24b3d78b4a91ab
1 #include <config.h>
2 #include <iostream>
3 #include <stdexcept>
4 #include <gnutls/gnutls.h>
5 #include <gnutls/gnutlsxx.h>
6 #include <cstring> /* for strlen */
8 /* A very basic TLS client, with anonymous authentication.
9 * written by Eduardo Villanueva Che.
12 #define MAX_BUF 1024
13 #define SA struct sockaddr
15 #define CAFILE "ca.pem"
16 #define MSG "GET / HTTP/1.0\r\n\r\n"
18 extern "C"
20 int tcp_connect(void);
21 void tcp_close(int sd);
25 int main(void)
27 int sd = -1;
28 gnutls_global_init();
30 try
33 /* Allow connections to servers that have OpenPGP keys as well.
35 gnutls::client_session session;
37 /* X509 stuff */
38 gnutls::certificate_credentials credentials;
41 /* sets the trusted cas file
43 credentials.set_x509_trust_file(CAFILE, GNUTLS_X509_FMT_PEM);
44 /* put the x509 credentials to the current session
46 session.set_credentials(credentials);
48 /* Use default priorities */
49 session.set_priority ("NORMAL", NULL);
51 /* connect to the peer
53 sd = tcp_connect();
54 session.set_transport_ptr((gnutls_transport_ptr_t) sd);
56 /* Perform the TLS handshake
58 int ret = session.handshake();
59 if (ret < 0)
61 throw std::runtime_error("Handshake failed");
63 else
65 std::cout << "- Handshake was completed" << std::endl;
68 session.send(MSG, strlen(MSG));
69 char buffer[MAX_BUF + 1];
70 ret = session.recv(buffer, MAX_BUF);
71 if (ret == 0)
73 throw std::runtime_error("Peer has closed the TLS connection");
75 else if (ret < 0)
77 throw std::runtime_error(gnutls_strerror(ret));
80 std::cout << "- Received " << ret << " bytes:" << std::endl;
81 std::cout.write(buffer, ret);
82 std::cout << std::endl;
84 session.bye(GNUTLS_SHUT_RDWR);
86 catch (std::exception &ex)
88 std::cerr << "Exception caught: " << ex.what() << std::endl;
91 if (sd != -1)
92 tcp_close(sd);
94 gnutls_global_deinit();
96 return 0;