getopt_long保留可选arg的默认值

时间:2013-01-13 03:55:14

标签: c getopt-long

我正在尝试使用getopt_long进行一些基本选项解析。我的具体问题是在未使用该选项时会覆盖默认的int值。我已经阅读了关于getopt的文档和一些解释,但没有看到任何关于保留默认值/可选参数的内容。

编译并运行它,我希望port / p的默认值为4567.当我指定没有选项,或者使用-p 5050时,一切正常。当我使用其他选项(-t)时,-p的值也会改变。

gcc -o tun2udp_dtls tun2udp_dtls.c
$ /tun2udp_dtls
port 4567 // correct
$ /tun2udp_dtls -p 5050
port 5050 // correct
$ ./tun2udp_dtls -t foo
port 0 // wtf!?

代码:

#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h> 

int main (int argc, char *argv[]) {
    // Vars
    char devname[128];
    int port = 4567;

    int c;
    while (1) {
        static struct option long_options[] = {
            {"tdev",  required_argument, NULL, 't'},
            {"port",  required_argument, NULL, 'p'},
            {0, 0, 0, 0}
        };
        int option_index = 0;
        c = getopt_long (argc, argv, "t:p:", long_options, &option_index);

        if (c == -1) break;
        switch (c) {
            case 't':
                strncpy(devname, optarg, sizeof(devname));
                devname[sizeof(devname)-1] = 0;
            case 'p':
                port = atoi(optarg);
            default:
                break;
        }
    }

    // Temporary debug printout
    printf("tdev '%s'\n", devname);
    printf("port %i\n", port);
}

1 个答案:

答案 0 :(得分:0)

break之前遗失case 'p':。这就是当处理“t”时控制达到port=atoi(optarg);的原因;然后atoi(optarg)为非数字设备名称返回0,并将此0分配给端口。