#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#define PORT 12344
int main(int argc, char** argv) {
int opt;
int server_fd, client_fd, epoll_fd;
int child_pid;
int port = PORT;
char* file = NULL;
/* Argparse */
static struct option long_options[] = {
{"file", required_argument, 0, 'f'},
{"port", optional_argument, 0, 'p'},
{"help", no_argument, 0, 'h'},
{NULL, 0, NULL, 0}
};
while ((opt = getopt_long(argc, argv, "f:p:h", long_options, NULL)) != -1) {
switch (opt) {
case 'f':
printf("file is: %s\n", optarg);
break;
case 'p':
port = atoi(optarg);
// since we will be listening on port > 1024 anyway, 0 is unused
if (!port) {
printf("not a valid port\n");
exit(1);
}
break;
case 'h':
printf("help message\n");
exit(0);
default:
break;
}
}
printf("end\n");
}
I am trying to build an application based on TCP. I want the program to take two arguments, a file parameter which specifies the configuration file, a number which is basically the port number to listen on The oher arguments work just fine. But, whenever I try to use the --port ABC option, the program crashes with a Segmentation fault.
What am I missing here?
optandoptargat that point?optional_argumentfor the port argument? That makes no sense.=. Either-p ABCor--port=ABC. If you use--port ABCyou will getoptarg == NULLcausing your segfault.'?'that can be returned on invalid options.=.