tags:

views:

217

answers:

2

Hi I am writtnig a simply Client - Server program. In this program I have to use getopt() library to get port number and ip address like this:

server -i 127.0.0.1 -p 10001

I do not know how can i get a values form optarg, to use they later in program.

And ofcourse sorry for my english. This is not my native language. :)

+1  A: 

How about like this:

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

Or in a more complete example:

#define BUFSIZE 16;

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;
    }
}
Kornel Kisielewicz
+2  A: 

You use a while loop to move through all the arguments and process them like so ...

#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;
}
mcdave
+1 for using strdup()