1. 程式人生 > >C++ 超強的URL解析演算法

C++ 超強的URL解析演算法

int parse_url(char *url, char **serverstrp, int *portp, char **pathstrp)
{
  char buf[256];
  int serverlen, numread=0;
  /* go through the url */

  /* reset url to point PAST the http:// */

  /* assume it's always 7 chars! */

  url = url+7;
  /* no http:// now... server is simply up to the next / or : */

  sscanf(url, "%255[^/:]", buf);
  serverlen = strlen(buf);
  *serverstrp = (char *)malloc(serverlen+1);
  strcpy(*serverstrp, buf);
  if(url[serverlen]==':')
  {
    /* get the port */

    sscanf(&url[serverlen+1], "%d%n", portp, &numread);
    /* add one to go PAST it */

    numread++;
  }
  else
  {
    *portp = 80;
  }
  /* the path is a pointer into the rest of url */

  *pathstrp = &url[serverlen+numread];
  return 0;
}