Parsing an url in c

Viewed 42

I'm trying to understand how the following code works, Im trying to parse an URL to get protocol, hostname and port:

void parse_url(char* url, char** hostname, char** port, char** path) {

//url in this example http://www.example.com:1234/res/page1.php?user=bob#account

char* p;
p = strstr(url, "://");

char* protocol = 0;
if (p) {
    protocol = url;
    *p = 0; //How does this statment make protocal = 'http'?
    p += 3;
}
else {
    p = url;
}

*hostname = p; 

while (*p && *p != ':' && *p != '/' && *p != '#') ++p; 
//as above am I corect that p will include everything up until the condition becomes false which in the case when it reaches ':'?


*port = "80";
if (*p == ':') {
    *p++ = 0;
    *port = p; 
}
while (*p && *p != '/' && *p != '#') ++p;

printf("hostname: %s\n", *hostname);
printf("port: %s\n", *port);

part of the confusion is the way the while is is also used for example

while(condtion){
//do something
}

this is the format Im used too however using pointers to change value is previous statments confuses me a little.

0 Answers
Related