1

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);
}
4

1 に答える 1

0

breakの前にありませんcase 'p':port=atoi(optarg);これが、「t」が処理されたときに制御が到達する理由です。次にatoi(optarg)、数値以外のデバイス名に対して 0 を返し、この 0 がポートに割り当てられます。

于 2013-01-13T04:05:33.770 に答える