对目标URL地址进行解析,得到三类信息:(1)主机地址,(2)端口(如果没有给出,默认就是80),(3)文件所在主机的具体路径名以及文件名
主要用到两个函数strstr(), strchr()用于查找字符串中是否有指定的字符串和字符,存在则返回对于地址,不存在则返回NULL。
源码:
#include <stdio.h>
#include <string.h>
int getUrlInfo(char *url, char* hostname, char *filepath);
int main() {
char hostname[100] = {0};
char filepath[100] = {0};
char *url = "http://www.baidu.com/eeefffggg/a.txt";
int ret = getUrlInfo(url, hostname, filepath);
if(ret != 0) {
printf("getUrlInfo error\n");
return -1;
}
printf("URL:%s\n", url);
printf("hostname:%s\nfilepath:%s\n", hostname, filepath);
return 0;
}
int getUrlInfo(char *str, char* hostname, char *filepath) {
char *pos = strstr(str, "//");
//printf("pos:%s\n", pos);
pos+=2;
if(*pos == '\0') {
printf("there is no filePath\n");
return -1;
}
char *pos2 = strchr(pos, '/');
strncpy(hostname, pos, pos2-pos);
strcpy(filepath, pos2+1);
return 0;
}
测试:
URL:http://www.baidu.com/eeefffggg/a.txt
hostname:www.baidu.com
filepath:eeefffggg/a.txt