How to parse URL (protocol, host, path) in C

1 Answer

0 votes
#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

*/

 



answered Jan 31, 2025 by avibootz

Related questions

1 answer 189 views
2 answers 450 views
2 answers 584 views
584 views asked Mar 31, 2018 by avibootz
1 answer 246 views
1 answer 314 views
2 answers 421 views
...