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.
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.
It is one of the numerous flaws of the getopt documentation: it does not state clearly that optarg must be copied for later use (using strdup(), for instance) because it may be overwritten by later options or just plain freed by getopt.
How about like this:
Or in a more complete example:
For more information see the documentation of Getopt.
You use a while loop to move through all the arguments and process them like so ...
In the case of an ip and port you don't need to store the strings. Just parse them and store the values in a sockaddr.