问题描述
我有此代码:
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确认:
您是对的,就是这样。