I'm completely new to C and my first project is to create a simple cURL-like HTTP request client... but first, I need to create a function that can parse a URL. I've created this function, and it seems to work quite well, but since I'm so new to the complexities of C, can someone check for any errors or to see if I can improve clock efficiency?
Example usage can be found here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void filterURLstring(char *weburl, char **protocol, char **username, char **password, char **host, char **port, char **path);
int main() {
char *text = "http://mhdfffffjddj:abc123@192.168.0.2:8888/servlet/rece/";
char *protocol, *username, *password, *host, *port, *path;
filterURLstring(text, &protocol, &username, &password, &host, &port, &path);
printf("Protocol:\"%s\"\n", protocol);
printf("Username:\"%s\"\n", username);
printf("Password:\"%s\"\n", password);
printf("Host:\"%s\"\n", host);
printf("Port:\"%s\"\n", port);
printf("Path:\"%s\"\n", path);
free(protocol);
free(username);
free(password);
free(host);
free(port);
free(path);
return 0;
}
void filterURLstring(char *weburl, char **protocol, char **username, char **password, char **host, char **port, char **path) {
char *postprotocol, *postuserinfo, *postusername, *login, *posthost, *posthostname, *hostloc, *postport;
int isPath;
if ((postprotocol = strstr(weburl, "://")) == NULL) {
printf("Input URL is invalid. Exiting...\n");
exit(1);
}
*protocol = malloc(sizeof(char) * (postprotocol - weburl + 1));
strncpy(*protocol, weburl, postprotocol - weburl);
postprotocol = (postprotocol + (*(postprotocol+3)=='/'?4:3));
if ((postuserinfo = strstr(postprotocol, "@")) != NULL) {
if ((postusername = strchr(postprotocol, ':')) != NULL) {
*password = malloc(sizeof(char) * (postuserinfo - postusername + 1));
strncpy(*password, postusername + 1, (postuserinfo - postusername - 1));
} else {
*password = NULL;
}
int userlen = (postusername?postusername:postuserinfo) - postprotocol;
*username = malloc(sizeof(char) * userlen + 1);
strncpy(*username, postprotocol, userlen);
}
hostloc = (postuserinfo?postuserinfo + 1:postprotocol);
if ((posthost = strchr(hostloc, '/')) == NULL) {
posthost = hostloc + strlen(hostloc);
isPath = 1;
}
if ((posthostname = strchr(hostloc, ':')) == NULL) {
posthostname = posthost;
}
*host = malloc(sizeof(char) * (posthostname - hostloc + 1));
strncpy(*host, hostloc, (posthostname - hostloc));
if (posthostname != posthost) {
posthostname++;
*port = malloc(sizeof(char) * (posthost - posthostname + 1));
strncpy(*port, posthostname, (posthost - posthostname));
} else {
*port = malloc(sizeof(char) * 2 + 1);
strncpy(*port, "80", 2);
}
if (isPath) {
*path = malloc(sizeof(char) * strlen(posthost));
strncpy(*path, posthost, strlen(posthost));
} else {
*path = calloc(1, 1);
}
}
I changed my code according to the answer. It can be seen here.