嵌入式 > 嵌入式开发 > 详情

学会在Linux下使用getopt函数来获取传入的参数

发布时间:2020-12-11 发布时间:
|

    之前写代码,要向程序中传参数,程序中使用argv[1]、argv[2]……

实际linux中的命令使用-r -l -i 等等,比如tcpdump,守护进程dhcp,顿时感觉自己脸好红,low到家了。

在linux下有一个函数叫getopt就可以写成-r -l -i 的形式,下面是一个使用openssl通信的程序,需要4个参数服务器ip -i、服务器端口-p、证书地址-c、私匙地址-s

代码如下,重点看while循环:

#include

#include  

#include  

#include  

#include

//#include

//openssl头文件  

#include  

#include

//getopt()

#include     

int main (int argc, char **argv)

{

//服务器套接字

struct sockaddr_in server_addr;  

bzero(&server_addr, sizeof(server_addr));

SSL_CTX *ctx=NULL;    /* SSL会话环境 */  

//使用SSL_CTX_new()创建会话环境,建立连接时要使用协议由TLS_server_method()来定。 

if( NULL==(ctx=SSL_CTX_new(TLS_server_method())) )     

{  

ERR_print_errors_fp(stdout); 

return -1;

}   

int oc;   /*选项字符 */

printf("optid=%d.\n", optind);

while( -1!=(oc=getopt(argc, argv, "i:p:c:s:")) )

{

switch(oc)

{

case 'i':

printf("i is %s.\n", optarg);

printf("optid=%d.\n", optind);

server_addr.sin_addr.s_addr = inet_addr(optarg);

break;

case 'p':

printf("p is %s.\n", optarg);

printf("optid=%d.\n", optind);

server_addr.sin_port = htons(atoi(optarg));

break;

case 'c':

printf("c is %s\n", optarg);

printf("optid=%d.\n", optind);

if( 0>=SSL_CTX_use_certificate_file(ctx, "./cacert.pem", SSL_FILETYPE_PEM) ) /* 为SSL会话加载用户证书 */  

{  

ERR_print_errors_fp(stdout);  

}     

break;

case 's':

printf("s is %s\n", optarg);

printf("optid=%d.\n", optind);

if( 0>=SSL_CTX_use_PrivateKey_file(ctx, "./privkey.pem", SSL_FILETYPE_PEM) ) /* 为SSL会话加载用户私钥 */  

{  

ERR_print_errors_fp(stdout); 

}   

break;

}

}

if( NULL!=ctx )  

{  

SSL_CTX_free(ctx);  

ctx=NULL;  

}  

return 0;

}

通过while循环检索程序启动时的参数,完成程序初始化工作。注意在给参数时-i、-p、-c、-s这4个的顺序是没有要求的。是不是很方便。




 


『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
定时器CTC模式的测试