Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from optarg

Tags:

c

getopt

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.

like image 369
Mateusz Avatar asked Dec 29 '09 09:12

Mateusz


1 Answers

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;
}
like image 145
mcdave Avatar answered Sep 21 '22 15:09

mcdave