最近在学openssl,想动手体验下其强大的功能,写了个简单的C/S通信程序,算是练习吧。

服务端:

#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <openssl/ssl.h>
int main( int argc, char * argv[] )
{
    int servfd, connfd;
    socklen_t clilen;
    struct sockaddr_in servaddr, cliaddr;
    char buff[512];
    pid_t chipid;
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons( 8888 );
    servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
    SSL_CTX * ctx;
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    if ( (ctx = SSL_CTX_new( SSLv23_server_method() )) == NULL )
    {
        printf( "error1" );
        return 0;
    }
    if ( SSL_CTX_use_certificate_file( ctx, argv[1], SSL_FILETYPE_PEM ) <= 0 )
    {
        printf( "error2" );
        return 0;
    }
    if ( SSL_CTX_use_PrivateKey_file( ctx, argv[2], SSL_FILETYPE_PEM ) <= 0 )
    {
        printf( "error3" );
        return 0;
    }
    if( !SSL_CTX_check_private_key( ctx ) )
    {
        printf( "keyerror" );
        return 0;
    }
    servfd = socket( AF_INET, SOCK_STREAM, 0 );
    bind( servfd, (struct sockaddr *)&servaddr, sizeof(servaddr) );
    listen( servfd, 10 );
    for ( ; ; )
    {
        SSL * ssl;
        clilen = sizeof(cliaddr);
        connfd = socket( AF_INET, SOCK_STREAM, 0 );
        connfd = accept( servfd, (struct sockaddr *)&cliaddr, &clilen );
        chipid = fork();
        if ( chipid != 0 )
            close( connfd );
        else
        {
            close( servfd );
            ssl = SSL_new( ctx );
            SSL_set_fd( ssl, connfd );
            SSL_accept( ssl );
            SSL_read( ssl, buff, 512 );
            printf( "%s\n", buff );
            SSL_shutdown( ssl );
            SSL_free( ssl );
            close( connfd );
            SSL_CTX_free( ctx );
            return 0;
        }
    }
}

客户端:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <openssl/ssl.h>
int main()
{
    int connfd;
    char buff[512] = {0};
    SSL_CTX * ctx;
    SSL * ssl;
    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons( 8888 );
    inet_pton( AF_INET, "127.0.0.1", &servaddr.sin_addr );
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    ctx = SSL_CTX_new( SSLv23_client_method() );
    connfd = socket( AF_INET, SOCK_STREAM, 0 );
    connect( connfd, (struct sockaddr *)&servaddr, sizeof(servaddr) );
    ssl = SSL_new( ctx );
    SSL_set_fd( ssl, connfd );
    SSL_connect( ssl );
    printf( "please input some words:" );
    scanf( "%s", buff );
    SSL_write( ssl, buff, 512 );
    return 0;
}

另外,有几篇文章对此介绍的比较详细:

http://blog.csdn.net/jinhill/article/details/3615626

http://blog.csdn.net/wangyongjun_cn/article/details/5295398

http://blog.sina.com.cn/s/blog_65bda7120100kmcs.html