Back to Code Snippets / Powrót do Strzępów Kodu


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void break_url(const char *url)
{
 char proto[16] = "";
 char user_to_port[512] = "";
 char path[256] = "";
 char user_pass[128] = ""; // zastanawiam się czy tu nie powinno być 512
 char host_port[512] = "";
 char user[64] = "";
 char pass[64] = "";
 int ret;
 char host[256] = "";
 unsigned short port = 0;

 // url == jakis url
 sscanf(url, "%15[^:]://%511[^/]%255s",
   proto,
   user_to_port,
   path);


 // korzystam z user_to_port otrzymanego wcześniej
 ret = sscanf(user_to_port, "%127[^@]@%511s",
   user_pass,
   host_port);

 if(ret == 2)
 {
   sscanf(user_pass, "%63[^:]:%63s", user, pass);
 }
 else
 {
   strcpy(host_port, user_to_port);
   // oba mają 512, więc overflow nie będzie
 }

 sscanf(host_port, "%255[^:]:%hu", host, &port);

 // Wypisz
 printf("Wejsciowy URL: %s\n", url);
 printf("Proto: %s\n", proto);
 if(*user) printf("User : %s\n", user);
 if(*pass) printf("Pass : %s\n", pass);
 printf("Host : %s\n", host);
 if(port) printf("Port : %u\n", port);
 if(*path) printf("Path : %s\n", path);
 putchar('\n');
}



int main(void)
{
 break_url("http://www.onet.pl");
 break_url("http://www.onet.pl/ala.html");
 break_url("http://tomek@www.onet.pl/ala.html");
 break_url("http://tomek:mapsa@www.onet.pl/ala.html");
 break_url("http://tomek:mapsa@www.onet.pl:1234/ala.html");
 break_url("http://tomek@www.onet.pl:1234/ala.html");
 break_url("http://www.onet.pl:1234/ala.html");
 break_url("http://www.onet.pl:1234");

 return 0;
}

Add a comment:

Nick:
URL (optional):
Math captcha: 6 ∗ 5 + 6 =