? ? 之前寫代碼,要向程序中傳參數(shù),程序中使用argv[1]、argv[2]……
實(shí)際linux中的命令使用-r -l -i 等等,比如tcpdump,守護(hù)進(jìn)程dhcp,頓時(shí)感覺自己臉好紅,low到家了。
在linux下有一個(gè)函數(shù)叫g(shù)etopt就可以寫成-r -l -i 的形式,下面是一個(gè)使用openssl通信的程序,需要4個(gè)參數(shù)服務(wù)器ip -i、服務(wù)器端口-p、證書地址-c、私匙地址-s
代碼如下,重點(diǎn)看while循環(huán):
#include
#include ?
#include ?
#include ?
#include
//#include
//openssl頭文件 ?
#include ?
#include
//getopt()
#include ? ??
int main (int argc, char **argv)
{
//服務(wù)器套接字
struct sockaddr_in server_addr; ?
bzero(&server_addr, sizeof(server_addr));
SSL_CTX *ctx=NULL; ? ?/* SSL會(huì)話環(huán)境 */ ?
//使用SSL_CTX_new()創(chuàng)建會(huì)話環(huán)境,建立連接時(shí)要使用協(xié)議由TLS_server_method()來定。?
if( NULL==(ctx=SSL_CTX_new(TLS_server_method())) ) ? ??
{ ?
ERR_print_errors_fp(stdout);?
return -1;
} ??
int oc; ? /*選項(xiàng)字符 */
printf("optid=%d. ", optind);
while( -1!=(oc=getopt(argc, argv, "i:p:c:s:")) )
{
switch(oc)
{
case 'i':
printf("i is %s. ", optarg);
printf("optid=%d. ", optind);
server_addr.sin_addr.s_addr = inet_addr(optarg);
break;
case 'p':
printf("p is %s. ", optarg);
printf("optid=%d. ", optind);
server_addr.sin_port = htons(atoi(optarg));
break;
case 'c':
printf("c is %s ", optarg);
printf("optid=%d. ", optind);
if( 0>=SSL_CTX_use_certificate_file(ctx, "./cacert.pem", SSL_FILETYPE_PEM) ) /* 為SSL會(huì)話加載用戶證書 */ ?
{ ?
ERR_print_errors_fp(stdout); ?
} ? ??
break;
case 's':
printf("s is %s ", optarg);
printf("optid=%d. ", optind);
if( 0>=SSL_CTX_use_PrivateKey_file(ctx, "./privkey.pem", SSL_FILETYPE_PEM) ) /* 為SSL會(huì)話加載用戶私鑰 */ ?
{ ?
ERR_print_errors_fp(stdout);?
} ??
break;
}
}
if( NULL!=ctx ) ?
{ ?
SSL_CTX_free(ctx); ?
ctx=NULL; ?
} ?
return 0;
}
通過while循環(huán)檢索程序啟動(dòng)時(shí)的參數(shù),完成程序初始化工作。注意在給參數(shù)時(shí)-i、-p、-c、-s這4個(gè)的順序是沒有要求的。是不是很方便。
?
評(píng)論