您好我正在编写一个简单的客户端-服务器程序。在这个程序中,我必须getopt()
像这样获取端口号和 IP 地址:
服务器 -i 127.0.0.1 -p 10001
我不知道如何从 optarg 获取值,以便稍后在程序中使用。
您使用 while 循环遍历所有参数并像这样处理它们......
#include <unistd.h>
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;
}
像这样怎么样:
char buf[BUFSIZE+1];
snprintf(buf,BUFSIZE,"%s",optarg);
或者在一个更完整的例子中:
#include <stdio.h>
#include <unistd.h>
#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的文档。
这是 getopt 文档的众多缺陷之一:它没有明确说明必须复制 optarg 以供以后使用(例如,使用 strdup()),因为它可能被以后的选项覆盖,或者只是被 getopt 简单地释放。
对于 ip 和端口,您不需要存储字符串。只需解析它们并将值存储在 sockaddr 中。
#include <arpa/inet.h> // for inet_ntop, inet_pton
#include <getopt.h> // for getopt, optarg
#include <netinet/in.h> // for sockaddr_in, etc
#include <stdio.h> // for fprintf, printf, stderr
#include <stdlib.h> // for atoi, EXIT_SUCCESS
#include <string.h> // for memset
#include <sys/socket.h> // 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 ---------- */