Add some basic argparsing

attempt-2
Nick Krichevsky 2018-08-27 12:27:59 -04:00
parent afd03376fe
commit 19449b3f1e
2 changed files with 60 additions and 0 deletions

51
client/http_client.c Normal file
View File

@ -0,0 +1,51 @@
#include "http_client.h"
#include "../common/http_message.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
bool print_rtt = false;
if (argc == 1) {
printf("%s", USAGE_STRING);
return 1;
}
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], RTT_FLAG) == 0) {
print_rtt = true;
}
}
if ((print_rtt && argc != 4) || (!print_rtt && argc != 3)) {
printf("%s", USAGE_STRING);
return 1;
}
char *dest = argv[argc - 2];
char *port = argv[argc - 1];
char *path_buffer = malloc(strlen(dest) + 1);
char *host_buffer = malloc(strlen(dest) + 1);
get_parts(dest, path_buffer, host_buffer);
printf("%s\n%s\n", path_buffer, host_buffer);
free(host_buffer);
free(path_buffer);
}
/**
* Get the parts of a url
*
* @param dest The destination specified by the user
* @param path_buffer A buffer large enough to hold the path of the dest
* @param host_buffer A buffer large enough to hold the host of the dest
*/
void get_parts(const char *dest, char *path_buffer, char *host_buffer) {
char *slash_cursor;
for (slash_cursor = dest; *slash_cursor != '\0' && *slash_cursor != '/'; slash_cursor++);
if (*slash_cursor == '\0') {
strcpy(path_buffer, "/");
strcpy(host_buffer, dest);
return;
}
strcpy(path_buffer, slash_cursor);
strncpy(host_buffer, dest, slash_cursor - dest);
}

9
client/http_client.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef HTTP_CLIENT_H
#define HTTP_CLIENT_H
#define RTT_FLAG "-p"
#define USAGE_STRING "Usage: ./http_client [-p] server_url port_number\n"
void get_parts(const char *dest, char *path_buffer, char *host_buffer);
#endif