I have a socket programming task to build a client/server chat. My code works when I type 3
value in terminal, but the problem is that I can't think of a way to put them all as an optional arguments and put some default value to work in any kind of that's example below,
./Client
./Client username
./Client username portNumber
./Client username portNumber serverAddress
int
main (int argc, char *argv[])
{
connection_info connection;
fd_set file_descriptors;
if (argc =! 4)
{
fprintf (stderr, "Usage: %s <IP> <port> <Name>\n", argv[0]);
exit (1);
}
connect_to_server(&connection, argv[1], argv[2], argv[3]);
}
Regarding the default value, just I need the username to be "Anynamous" and the ip is "localhost" while the port is 3000
CodePudding user response:
I want the username to be "Anynamous" and the ip is "localhost" while the port is 3000
Set up for those default values and change them if enough arguments passed.
int main (int argc, char *argv[]) {
const char *username = "Anynamous"; // Or maybe "Anonymous"
const char *ip = "localhost";
int port = 3000;
if (argc >= 2) username = argv[1];
if (argc >= 3) ip = argv[2];
if (argc >= 4) port = atoi(argv[3]); // Could add some conversion checking here.
connection_info connection;
connect_to_server(&connection, username, ip, port);
fd_set file_descriptors;
// ...
}