vtun如何解析启动客户端或服务器的命令行参数?
Usage: Server: vtund <-s> [-f file] [-P port] [-L local address] Client: vtund [-f file] [-p] [-m] [-t timeout] <host profile> <server address>
预备知识:
-s –f –P 等称为选项;
file port称为选项对应的参数;
host file server address ——暂且称它们为非选项字符串吧。
解析代码在main.c中。
在vtun源码中是这样实现的:
1234567891011121314151617181920212223242526272829303132333435363738394041 | if(!svr) { usage(); exit(1); }hst = argv[optind++]; //argv[optind++]指的是第一个非选项字符串host或者server,可以理解为本次会话的名称。 if( !(host = find_host(hst)) ) { vtun_syslog(LOG_ERR,"Host %s not found in %s", hst, vtun.cfg_file); exit(1); }vtun.svr_name = strdup(argv[optind]); //上面optind加1了,所以此处的argv[optind]指的是profile或address. }
void usage(void) { printf("VTun ver %s\n", VTUN_VER); printf("Usage: \n"); printf(" Server:\n"); printf("\tvtund <-s> [-f file] [-P port] [-L local address]\n"); printf(" Client:\n"); /* I don't think these work. I'm disabling the suggestion - bish 20050601*/ printf("\tvtund [-f file] " /* [-P port] [-L local address] */ "[-p] [-m] [-t timeout] <host profile> <server address>\n");} |
为充分理解getopt和argc,argv的关系,再看一个例子
123456789101112131415161718192021222324252627282930313233343536373839 | root@ubuntu:~/eclipseworkspace# ./a.out -b barg ee ff option=b, opt=98, optarg=barg, optind=3, optopt=0after getopt,optind=3 //此时optind在ee位置argc-optind=2argv[optind]=eeargv[optind++]=ee*/ |