c - getopt_long 保留可选参数的默认值

标签 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);
}

最佳答案

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

关于c - getopt_long 保留可选参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300515/

相关文章:

c++ - 我可以访问地址零吗?

c - getopt_long_only : how to prevent the next option as being taken as argument for the previous option with "required_argument" flag

perl - Perl 的 Getopt::Long 如何发现缺少强制参数的参数?

perl - 如何访问选项子中的 Getopt::Long 选项值?

ios - Objective-c:当所有线程完成时返回

c - 如何使用 C 巧妙地转换日期时间值中的秒数

我可以在 C 中将 char* 传递给 const char* 吗?

c - 从文件中读取单词并在 C 中逐行加密每个单词

c - 如何确定缺少所需的选项参数?

Perl Getopt::Long 支持参数空格