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、通常、さまざまなスイッチに一致する変数を宣言します。これにより、引数の解析が完了したら、後でそれらのスイッチを操作できます。引数の処理中にすぐに実行できるいくつかの引数。

たとえば、-p引数の場合と同様に、コマンドaddressからのアドレスを格納するための変数がある場合があります。-i

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 に答える