如何从optarg中获取值

嗨,我正在写一个简单的客户端 – 服务器程序。 在这个程序中,我必须使用getopt()来获取端口号和ip地址,如下所示:

server -i 127.0.0.1 -p 10001

我不知道如何从optarg中获取值,以便稍后在程序中使用。

这样怎么样:

 char buf[BUFSIZE+1]; snprintf(buf,BUFSIZE,"%s",optarg); 

或者在一个更完整的例子中:

 #include  #include  #define BUFSIZE 16 int main( int argc, char **argv ) { char c; char port[BUFSIZE+1]; char addr[BUFSIZE+1]; while(( c = getopt( argc, argv, "i:p:" )) != -1 ) switch ( c ) { case 'i': snprintf( addr, BUFSIZE, "%s", optarg ); break; case 'p': snprintf( port, BUFSIZE, "%s", optarg ); break; case '?': fprintf( stderr, "Unrecognized option!\n" ); break; } return 0; } 

有关更多信息,请参阅Getopt的文档。

你使用while循环遍历所有参数并像这样处理它们……

 #include  int main(int argc, char *argv[]) { int option = -1; char *addr, *port; while ((option = getopt (argc, argv, "i:p:")) != -1) { switch (option) { case 'i': addr = strdup(optarg); break; case 'p': port = strdup(optarg); break; default: /* unrecognised option ... add your error condition */ break; } } /* rest of program */ return 0; } 

这是getopt文档的众多缺陷之一:它没有明确说明必须复制optarg以供以后使用(例如使用strdup()),因为它可能被后面的选项覆盖,或者只是由getopt释放。

在ip和port的情况下,您不需要存储字符串。 只需解析它们并将值存储在sockaddr中。

 #include  // for inet_ntop, inet_pton #include  // for getopt, optarg #include  // for sockaddr_in, etc #include  // for fprintf, printf, stderr #include  // for atoi, EXIT_SUCCESS #include  // for memset #include  // for AF_INET int main(int argc, char *argv[]) { struct sockaddr_in sa; char c; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = 0; while ((c = getopt(argc, argv, "i:p:")) != -1) { switch (c) { case 'p': sa.sin_port = htons(atoi(optarg)); break; case 'i': inet_pton(AF_INET, optarg, &(sa.sin_addr)); break; case '?': fprintf(stderr, "Unknown option\n"); break; } /* ----- end switch ----- */ } char str[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); printf("%s:%d\n", str, ntohs(sa.sin_port)); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */