#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void parse_url(const char *url) {
const char *protocol_end = strstr(url, "://");
if (protocol_end == NULL) {
fprintf(stderr, "Invalid URL format (missing ://)\n");
return;
}
size_t protocol_len = protocol_end - url;
char *protocol = (char *)malloc(protocol_len + 1);
if (protocol == NULL) {
perror(")malloc(protocol_len + 1)");
return;
}
strncpy(protocol, url, protocol_len);
protocol[protocol_len] = '\0';
printf("Protocol: %s\n", protocol);
const char *host_start = protocol_end + 3; // Skip "://"
const char *path_start = strchr(host_start, '/');
char *host = NULL;
if (path_start != NULL) {
size_t host_len = path_start - host_start;
host = (char *)malloc(host_len + 1);
if (host == NULL) {
perror("malloc(host_len + 1)");
free(protocol);
return;
}
strncpy(host, host_start, host_len);
host[host_len] = '\0';
printf("Host: %s\n", host);
} else {
host = strdup(host_start); // Host only without path
if (host == NULL) {
perror("strdup(host_start)");
free(protocol);
return;
}
printf("Host: %s\n", host);
path_start = host_start + strlen(host_start);
}
char *path = strdup(path_start);
if (path == NULL) {
perror("strdup(path_start)");
free(protocol);
free(host);
return;
}
printf("Path: %s\n", path);
free(protocol);
free(host);
free(path);
}
int main() {
const char *url = "https://www.collectivesolver.com/path/to/resource";
parse_url(url);
return 0;
}
/*
run:
Protocol: https
Host: www.collectivesolver.com
Path: /path/to/resource
*/