getopt忽略命令行参数

问题描述

我有此代码:

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之后的每个参数。

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

谢谢。

解决方法

将评论转换为答案。

您应将// omitted的注释替换为printf("Found: %c '%s'\n",opt,optarg);,以便您和我们都能看到问题所在。也许您省略的代码引起了麻烦-这些事情是已知的。请阅读有关如何创建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确认:

您是对的,就是这样。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...