I want to use the default host name localhost and port 8080 when I don't specify the arguments.
server.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <dirent.h>
#include <sys/wait.h>
#include <assert.h>
#include "command.h"
#include "send.h"
#include "receive.h"
#define DEFAULT_PORT 8080
void checkError(int status)
{
if (status < 0) {
fprintf(stderr, "Process %d: socket error: [%s]\n", getpid(),strerror(errno));
exit(-1);
}
}
void handleNewConnection(int chatSocket);
int main(int argc,char* argv[])
{
short int port;
port = atoi(argv[1]); //When the argument is specified
(...)
client.c
(...)
void doLSCommand(int sid);
void doExitCommand(int sid);
void doGETCommand(int sid);
void doPUTCommand(int sid);
void doSIZECommand(int sid);
int doMGETCommand(int sid);
int main(int argc,char* argv[])
{
char fName[BUF_SIZE];
char* host;
short int port;
host = atoi(argv[1]); //when argument specified in command line
port = atoi(argv[2]); //when argument specified in command line
(...)
I used atoi to get the arguments when they're provided but I don't know how to set defaults if they are not provided.
There are two arguments to the main
function: argc
and argv
.
argc
is a number of command line arguments passed and argv
is the array of command line arguments.
See: https://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html
In your case, you can check the argc
first for how many arguments has the user passed to your program and act accordingly.
So, for the host it could be:
char* host;
if (argc > 1) {
host = argv[1];
}
else {
host = DEFAULT_HOST;
}
and for the port number:
int port;
if (argc > 2) {
port = atoi(argv[2]);
}
else {
port = DEFAULT_PORT;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.