1

我知道这个话题可能已经被写死了,但我一直找不到任何让我理解它的东西。我需要在命令行中输入一个值(例如 IP 地址)并将其传递给函数。

下面是我的 getopt_long 函数。

while (1)
{
    static struct option long_options[] =
    {
        /* Options */
    {"send",       no_argument,       0, 's'}, /* args s and r have no function yet */
    {"recieve",    no_argument,       0, 'r'},
    {"file",       required_argument, 0, 'f'}, 
    {"destip",     required_argument, 0, 'i'},
    {"destport",   required_argument, 0, 'p'},
    {"sourceip",   required_argument, 0, 'o'},
    {"sourceport", required_argument, 0, 't'},
    {0, 0, 0, 0}
    };

   int option_index = 0;

   c = getopt_long (argc, argv, "srf:d:i:p:o:t:",
                long_options, &option_index);

              /* Detect the end of the options. */
   if (c == -1)
     break;

   switch (c)
     {
     case 0:
       /* If this option set a flag, do nothing else now. */
       if (long_options[option_index].flag != 0)
         break;
       printf ("option %s", long_options[option_index].name);
       if (optarg)
         printf (" with arg %s", optarg);
       printf ("\n");
       break;

     case 's':
       puts ("option -s\n");
       break;

     case 'r':
       puts ("option -r\n");
       break;

     case 'f':
       printf ("option -f with value `%s'\n", optarg);
       break;

     case 'i':
       printf ("option -i with value `%s'\n", optarg);
       break;

     case 'p':
       printf ("option -p with value `%s'\n", optarg);
       break;

     case 'o': 
       printf ("option -o with value `%s'\n", optarg);
       break;

     case 't': 
       printf ("option -t with value `%s'\n", optarg);
       break;

     case '?':
       /* Error message printed */
       break;

     default:
       abort ();
     }
}

/* Print any remaining command line arguments (not options). */
if (optind < argc)
{
    printf ("non-option ARGV-elements: ");
    while (optind < argc)
    printf ("%s ", argv[optind++]);
    putchar ('\n');
}

这是我需要价值的地方(非常标准的 tcp 结构的一部分)

ip->iph_sourceip = inet_addr(arg);

我该如何正确地做到这一点?我进行了相当多的研究,尽管许多都涵盖了类似的主题,但它们似乎并不能很好地解释我的问题。

4

1 回答 1

1

使用 时getopt,您通常会声明与各种开关匹配的变量,以便稍后在参数解析完成后对它们进行操作;您可以在参数处理期间立即采取行动的一些参数。

例如,您可能有一个address用于存储-i命令地址的变量,与 -p 参数类似:

in_addr_t address;
int port;

// ... later in your switch statement:
switch (c)
{
    // ...

   case 'i':
       printf("option -i with value `%s'\n", optarg);
       address = inet_addr(optarg);
       break;
   case 'p':
       printf("option -p with value `%s'\n", optarg);
       // be sure to add handling of bad (non-number) input here
       port = atoi(optarg);
       break;
    // ...
}

// later in your code, e.g. after arg parsing, something like:
send_tcp(address, port);
于 2012-07-18T23:29:19.097 回答