Make it find strlen.
[gnutls.git] / doc / examples / ex-cxx.cpp
blob3233aa2f16c901ac97f00146165d7da3b7d8de24
1 #if HAVE_CONFIG_H
2 # include <config.h>
3 #else
4 #endif
5 #include <iostream>
6 #include <stdexcept>
7 #include <gnutls/gnutls.h>
8 #include <gnutls/gnutlsxx.h>
10 #include <string.h> /* for strlen */
12 /* A very basic TLS client, with anonymous authentication.
13 * written by Eduardo Villanueva Che.
16 #define MAX_BUF 1024
17 #define SA struct sockaddr
19 #define CAFILE "ca.pem"
20 #define MSG "GET / HTTP/1.0\r\n\r\n"
22 extern "C"
24 int tcp_connect(void);
25 void tcp_close(int sd);
29 int main(void)
31 int sd = -1;
32 gnutls_global_init();
34 try
37 /* Allow connections to servers that have OpenPGP keys as well.
39 gnutls::client_session session;
41 /* X509 stuff */
42 gnutls::certificate_credentials credentials;
45 /* sets the trusted cas file
47 credentials.set_x509_trust_file(CAFILE, GNUTLS_X509_FMT_PEM);
48 /* put the x509 credentials to the current session
50 session.set_credentials(credentials);
52 /* Use default priorities */
53 session.set_priority ("NORMAL", NULL);
55 /* connect to the peer
57 sd = tcp_connect();
58 session.set_transport_ptr((gnutls_transport_ptr_t) sd);
60 /* Perform the TLS handshake
62 int ret = session.handshake();
63 if (ret < 0)
65 // gnutls_perror(ret);
66 throw std::runtime_error("Handshake failed");
68 else
70 std::cout << "- Handshake was completed" << std::endl;
73 session.send(MSG, strlen(MSG));
74 char buffer[MAX_BUF + 1];
75 ret = session.recv(buffer, MAX_BUF);
76 if (ret == 0)
78 throw std::runtime_error("Peer has closed the TLS connection");
80 else if (ret < 0)
82 throw std::runtime_error(gnutls_strerror(ret));
85 std::cout << "- Received " << ret << " bytes:" << std::endl;
86 std::cout.write(buffer, ret);
87 std::cout << std::endl;
89 session.bye(GNUTLS_SHUT_RDWR);
91 catch (std::exception &ex)
93 std::cerr << "Exception caught: " << ex.what() << std::endl;
96 if (sd != -1)
97 tcp_close(sd);
99 gnutls_global_deinit();
101 return 0;