【问题标题】:getopt ignoring command line argumentsgetopt 忽略命令行参数
【发布时间】:2020-11-02 23:34:49
【问题描述】:

我有这个代码:

char *host = NULL;
int port = 53;
int opt;

while ((opt = getopt(argc, argv, "s:p:f:")) != -1) {
    switch (opt) {
        case 's':
            host = optarg;
            if (!isValidIpAddress(host)) {
                struct hostent *host_info = gethostbyname(host);
                if (host_info == NULL) {
                    fprintf(stderr, "Domain not found!\n");
                    return 1;
                }
                struct in_addr **address_list = (struct in_addr **)host_info->h_addr_list;
                strcpy(host, inet_ntoa(*address_list[0]));
            }
            break;
        case 'p':
            port = atoi(optarg);
            if (port < 1 || port > 65535) {
                fprintf(stderr, "Invalid port number!\n");
                return 1;
            }
            break;
        case 'f':
            // does nothing at the moment
            break;
        default:
            printf("Option incorrect\n");
            return 1;
        }
}

当我使用./test -s google.com -p 40 运行它时,getopt() 会处理 -s 参数,但似乎忽略了 -p(在第一个循环后返回 -1)。

编辑:它忽略 -s 之后的每个参数。

我确定问题非常简单,一旦有人指出,我会感到很愚蠢,但我就是想不通。

提前谢谢你。

【问题讨论】:

  • 您是否在sp 的省略代码中使用optargp的代码后面没有break是故意的吗?
  • 您应该用printf("Found: %c '%s'\n", opt, optarg); 替换您的// omitted cmets,以便您和我们可以看到发现了什么。也许你省略的代码造成了麻烦——这样的事情已经知道了。请阅读有关如何创建 MCVE(Minimal, Complete, Verifiable Example — 或 MRE 或 SO 现在使用的任何名称)或 SSCCE(Short, Self-Contained, Correct Example)的信息。
  • 添加调试打印并在您的片段周围包装最少的代码,我无法重现您的麻烦。这表明问题出在您未显示的代码中。请按照之前的要求创建 MCVE。
  • @MihaiMaruseac 是的,我是。丢失的休息不是故意的,但它并不能解决问题。
  • 你的问题可能是strcpy(host, inet_ntoa(*address_list[0]));这行。因为您在参数列表中将host 设置为指向optarg 指向的位置,并且optarg 指向asd,并且扩展的主机名比asd 长,所以您的代码在参数列表中到处乱写,让一切(尤其是getopt())陷入混乱。

标签: c getopt


【解决方案1】:

将 cmets 转换为答案。

您应该用printf("Found: %c '%s'\n", opt, optarg); 替换您的// omitted cmets,以便您和我们可以看到发现了什么。也许你省略的代码造成了麻烦——这样的事情是众所周知的。请阅读有关如何创建 MCVE(Minimal, Complete, Verifiable Example — 或 MRE 或 SO 现在使用的任何名称)或 SSCCE(Short, Self-Contained, Correct Example)的信息。

提供额外的代码。

您的问题可能是strcpy(host, inet_ntoa(*address_list[0])); 行。因为您在参数列表中将host 设置为指向optarg 指向的位置,并且optarg 指向asd,并且扩展的主机名比asd 长,所以您的代码在参数列表中到处乱写,让一切(尤其是getopt())陷入混乱。

comment 证实了这一点:

你是对的,就是这样。

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多