最近在学openssl,想动手体验下其强大的功能,写了个简单的C/S通信程序,算是练习吧。
服务端:
#include
#include
#include
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#include
#include
#include
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;
}
阅读(2390) | 评论(0) | 转发(0) |