linux 带参数程序 getopt 模板,学会在Linux下使用getopt函数来获取传入的参数

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

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

489b6f6018e281af35e01ffd6e70d9be.png

在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个的顺序是没有要求的。是不是很方便。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值