Files
ft_ping/src/opt_parse.c

74 lines
1.5 KiB
C

#include <help.h>
#include <opt_parse.h>
#include <ping.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
int handle_long_args(char **av, args_t *args) {
OPT_WHILE {
if (strncmp((*av) + 2, options[i].name, strlen(options[i].name)) == 0) {
OPT_HANDLE(i);
}
i++;
}
print_parse_err(INVALID_OPT, (*av) + 2);
return EXIT_FAILURE;
}
int opt_parse(char **av, args_t *args) {
av++;
while (*av != NULL) {
char *a = *av;
if (*a == '-') {
char opt = *(a + 1);
if (!opt) {
print_parse_err(MISSING_HOST, 0);
return EX_USAGE;
} else if (opt == '-') {
int ret = handle_long_args(av, args);
if (ret != EXIT_SUCCESS) {
if (ret == EX_USAGE)
print_parse_err(NEED_ARG, (*av) + 2);
return ret;
}
} else {
OPT_WHILE {
if (opt == options[i].opt) {
OPT_HANDLE(i)
}
i++;
}
if (i == OPT_NB) {
print_parse_err(INVALID_OPT, a);
return EXIT_FAILURE;
}
}
} else {
if (args->hosts == NULL) {
args->hosts = calloc(sizeof(char *), 2);
args->hosts[0] = *av;
args->hosts[1] = NULL;
} else {
int i;
for (i = 0; args->hosts[i] != NULL; ++i)
;
char **old = args->hosts;
args->hosts = reallocarray(old, i + 2, sizeof(char *));
if (args->hosts == NULL)
return EXIT_FAILURE;
args->hosts[i] = *av;
args->hosts[i + 1] = NULL;
}
}
av++;
}
return EXIT_SUCCESS;
}
// 127.0.0.1 localhost : no error wtf EZ 42 parsing + ratio
// -v 127.0.0.1