Corrected allocation check
[gnutls.git] / doc / examples / ex-client-anon.c
blobba56934461a440f1fa460b5c1e2a38e2ca491a80
1 /* This example code is placed in the public domain. */
3 #ifdef HAVE_CONFIG_H
4 #include <config.h>
5 #endif
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <arpa/inet.h>
13 #include <unistd.h>
14 #include <gnutls/gnutls.h>
16 /* A very basic TLS client, with anonymous authentication.
19 #define MAX_BUF 1024
20 #define MSG "GET / HTTP/1.0\r\n\r\n"
22 extern int tcp_connect (void);
23 extern void tcp_close (int sd);
25 int
26 main (void)
28 int ret, sd, ii;
29 gnutls_session_t session;
30 char buffer[MAX_BUF + 1];
31 gnutls_anon_client_credentials_t anoncred;
32 /* Need to enable anonymous KX specifically. */
34 gnutls_global_init ();
36 gnutls_anon_allocate_client_credentials (&anoncred);
38 /* Initialize TLS session
40 gnutls_init (&session, GNUTLS_CLIENT);
42 /* Use default priorities */
43 gnutls_priority_set_direct (session, "PERFORMANCE:+ANON-ECDH:+ANON-DH",
44 NULL);
46 /* put the anonymous credentials to the current session
48 gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);
50 /* connect to the peer
52 sd = tcp_connect ();
54 gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
56 /* Perform the TLS handshake
60 ret = gnutls_handshake (session);
62 while (ret < 0 && gnutls_error_is_fatal (ret) == 0);
64 if (ret < 0)
66 fprintf (stderr, "*** Handshake failed\n");
67 gnutls_perror (ret);
68 goto end;
70 else
72 printf ("- Handshake was completed\n");
75 gnutls_record_send (session, MSG, strlen (MSG));
77 ret = gnutls_record_recv (session, buffer, MAX_BUF);
78 if (ret == 0)
80 printf ("- Peer has closed the TLS connection\n");
81 goto end;
83 else if (ret < 0)
85 fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
86 goto end;
89 printf ("- Received %d bytes: ", ret);
90 for (ii = 0; ii < ret; ii++)
92 fputc (buffer[ii], stdout);
94 fputs ("\n", stdout);
96 gnutls_bye (session, GNUTLS_SHUT_RDWR);
98 end:
100 tcp_close (sd);
102 gnutls_deinit (session);
104 gnutls_anon_free_client_credentials (anoncred);
106 gnutls_global_deinit ();
108 return 0;