学会在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、《桃花源记》战神觉醒手游萌宠助战新版本1688
  2. 2、触控游戏获天蚕土豆《武动乾坤》手游独家代理权626
  3. 3、威震天界9377《吞天记》斗战场上演诛仙封神961
  4. 4、《神明秩序:幻域神姬》今年绝对不跳票4563
  5. 5、燃系3D动作《超能战区》曝光9.2日越狱首发4510
  6. 6、《永恒战记》人物原画首曝精美日系画风闪亮登场1282
  7. 7、《阿凡达》IMAX版票房占比达30%,重映票房累计14.8亿元2016
  8. 8、人靠衣装马靠鞍《烈焰龙城》时装系统首曝3524
  9. 9、再度开启国服《怪物弹珠》如何扎根中国市场510
  10. 10、玩家大战主策:一骑当千跨服战给你好看2533
全部评论(0)
我也有话说
0
收藏
点赞
顶部