Sync with TP.
[gnutls.git] / doc / examples / ex-client1.c
blob16305a682b5e104492ccbef8ad3821a6a038eba7
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-DH:!ARCFOUR-128",
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
58 ret = gnutls_handshake (session);
60 if (ret < 0)
62 fprintf (stderr, "*** Handshake failed\n");
63 gnutls_perror (ret);
64 goto end;
66 else
68 printf ("- Handshake was completed\n");
71 gnutls_record_send (session, MSG, strlen (MSG));
73 ret = gnutls_record_recv (session, buffer, MAX_BUF);
74 if (ret == 0)
76 printf ("- Peer has closed the TLS connection\n");
77 goto end;
79 else if (ret < 0)
81 fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
82 goto end;
85 printf ("- Received %d bytes: ", ret);
86 for (ii = 0; ii < ret; ii++)
88 fputc (buffer[ii], stdout);
90 fputs ("\n", stdout);
92 gnutls_bye (session, GNUTLS_SHUT_RDWR);
94 end:
96 tcp_close (sd);
98 gnutls_deinit (session);
100 gnutls_anon_free_client_credentials (anoncred);
102 gnutls_global_deinit ();
104 return 0;