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.
How about like this:
char buf[BUFSIZE+1];
snprintf(buf,BUFSIZE,"%s",optarg);
Or in a more complete example:
#include <stdio.h>
#include <unistd.h>
#define BUFSIZE 16
int main( int argc, char **argv )
{
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;
}
return 0;
}
For more information see the documentation of Getopt.