C getopt_long保留可选参数的默认值

C getopt_long保留可选参数的默认值,c,getopt-long,C,Getopt Long,我正在尝试使用getopt_long进行一些基本的选项解析。我的具体问题是,当不使用该选项时,会覆盖默认的int值。我已经阅读了关于getopt的文档和一些解释,但没有看到任何关于保留默认值/可选参数的内容 编译并运行它时,我希望端口/p的默认值为4567。当我不指定任何选项,或者使用-p5050时,一切正常。当我打开其他选项-t时,-p的值也会改变 gcc -o tun2udp_dtls tun2udp_dtls.c $ /tun2udp_dtls port 4567 // correct $

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

编译并运行它时,我希望端口/p的默认值为4567。当我不指定任何选项,或者使用-p5050时,一切正常。当我打开其他选项-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);
}

案例“p”之前缺少中断:。这就是为什么控件到达port=atoiptarg;当t被处理时;然后AtiopTarg为非数字设备名返回0,并且该0被分配到端口。

哈哈,这也让我明白了。谢谢你的有用的帖子