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

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

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

 学会在Linux下使用getopt函数来获取传入的参数_设计制作_测量仪表

在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 m     ai   n (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_erro     rs   _fp(stdout);

return -1;

}

int oc;   /*选项     字符   */

printf("op     ti   d=%d.\n", op  TI nd);

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

{

switch(oc)

{

case 'i':

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

printf("op  TI d=%d.\n", op  TI nd);

server_addr.sin_addr.s_addr = inet_addr(optarg);

break;

case 'p':

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

printf("op  TI d=%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_certifica     te   _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个的顺序是没有要求的。是不是很方便。




90
71
0
18

相关资讯

  1. 1、吉恒达总经理张军辉|谈散热风扇在工业领域的现状和未来3082
  2. 2、拥抱工业物联网英威腾解决监控系统痛点3105
  3. 3、腾通讯宣布未来五年投入5000亿,用于新基建的进一步布局4690
  4. 4、工业互联网APP产业发展现状及趋势3565
  5. 5、浅谈C语言return语句和main函数的返回值4788
  6. 6、市场爆发前夜,这20家企业争夺亿万级底盘肥肉1457
  7. 7、全国政协委员李彦宏的五份提案都在关注哪些话题?1725
  8. 8、一个合格FPGA工程师的基本要求1057
  9. 9、电力现货市场“中国化”实践分析3577
  10. 10、自适应负载调整和动态功率控制实现模拟输出的高效散热设计2417
全部评论(0)
我也有话说
0
收藏
点赞
顶部