// parse url 解析 url c c++ 代码 rfc 2068
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 解析url,作为示例,很多情况没考虑,比如说user,pass之类的
int parse_url(char *url, char **serverstrp, int *portp, char **pathstrp)
{
char buf[256];
int serverlen, numread=0;
// 跳过"http://" ,例"http://www.a.cn"->"www.a.cn"
url = url+7;
// 输入url直到遇到'/'和':'符号
sscanf(url, "%255[^/:]", buf);
serverlen = strlen(buf);
*serverstrp = (char *)malloc(serverlen+1);
strcpy(*serverstrp, buf);
if(url[serverlen]==':')
{
// 获取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;
}
int main()
{
char url[256] = "http://www.a.cn:80//index.html";
char pathstr[256] = {'/0'};
char szserverstrp[256] = {'/0'};
char* serverstrp = szserverstrp;
char* pathstrp = &pathstr[0];
int port;
parse_url(url,&serverstrp,&port,&pathstrp);
printf("%s/n%s/n%d/n%s/n",url,serverstrp,port,pathstrp);
return 0;
}
标签:serverlen,url,char,int,pathstrp,serverstrp,解析
From: https://blog.51cto.com/u_16156420/6449081