How to get a value from optarg

Mateusz picture Mateusz · Dec 29, 2009 · Viewed 39.3k times · Source

Hi I am writing a simple client-server program. In this program I have to use getopt() to get the port number and ip address like this:

server -i 127.0.0.1 -p 10001

I do not know how can I get values from optarg, to use later in the program.

Answer

mcdave picture mcdave · Dec 29, 2009

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;
}