1 /* cli.cpp - Minimal ssleay client for Unix
2 30.9.1996, Sampo Kellomaki <sampo@iki.fi> */
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
13 #include "rsa.h" /* SSLeay stuff */
20 #define CHK_NULL(x) if ((x)==NULL) exit (1)
21 #define CHK_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
22 #define CHK_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(2); }
28 struct sockaddr_in sa;
35 SSL_load_error_strings();
36 ctx = SSL_CTX_new (); CHK_NULL(ctx);
38 /* ----------------------------------------------- */
39 /* Create a socket and connect to server using normal socket calls. */
41 sd = socket (AF_INET, SOCK_STREAM, 0); CHK_ERR(sd, "socket");
43 memset (&sa, '\0', sizeof(sa));
44 sa.sin_family = AF_INET;
45 sa.sin_addr.s_addr = inet_addr ("127.0.0.1"); /* Server IP */
46 sa.sin_port = htons (1111); /* Server Port number */
48 err = connect(sd, (struct sockaddr*) &sa,
49 sizeof(sa)); CHK_ERR(err, "connect");
51 /* ----------------------------------------------- */
52 /* Now we have TCP conncetion. Start SSL negotiation. */
54 ssl = SSL_new (ctx); CHK_NULL(ssl);
56 err = SSL_connect (ssl); CHK_SSL(err);
58 /* Following two steps are optional and not required for
59 data exchange to be successful. */
61 /* Get the cipher - opt */
63 printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
65 /* Get server's certificate (note: beware of dynamic allocation) - opt */
67 server_cert = SSL_get_peer_certificate (ssl); CHK_NULL(server_cert);
68 printf ("Server certificate:\n");
70 str = X509_NAME_oneline (X509_get_subject_name (server_cert));
72 printf ("\t subject: %s\n", str);
75 str = X509_NAME_oneline (X509_get_issuer_name (server_cert));
77 printf ("\t issuer: %s\n", str);
80 /* We could do all sorts of certificate verification stuff here before
81 deallocating the certificate. */
83 X509_free (server_cert);
85 /* --------------------------------------------------- */
86 /* DATA EXCHANGE - Send a message and receive a reply. */
88 err = SSL_write (ssl, "Hello World!", strlen("Hello World!")); CHK_SSL(err);
90 shutdown (sd, 1); /* Half close, send EOF to server. */
92 err = SSL_read (ssl, buf, sizeof(buf) - 1); CHK_SSL(err);
94 printf ("Got %d chars:'%s'\n", err, buf);