-1

我正在解析 C 中的 http 标头,需要从完整的 url 中减去主机名。

我设法获得了完整的 url ( http://www.example.com/hello.html ) 和路径名 (hello.html) 但不能减去 (full url - path name) 主机名 (example.com) .

Example full url: http://www.example.com/hello.html - DONE
host name: example.com - TODO
path name: /hello.html - DONE

任何帮助,将不胜感激。谢谢

4

2 回答 2

3

您可以使用memcpy,如下所示:

char *url = "http://www.example.com/hello.html";
// find the last index of `/`
char *path = url + strlen(url);
while (path != url && *path != '/') {
   path--;
}
// Calculate the length of the host name
int hostLen = path-url;
// Allocate an extra byte for null terminator
char *hostName = malloc(hostLen+1);
// Copy the string into the newly allocated buffer
memcpy(hostName, url, hostLen);
// Null-terminate the copied string
hostName[hostLen] = '\0';
...
// Don't forget to free malloc-ed memory
free(hostName);

这是关于 ideone 的演示

于 2013-05-02T16:37:55.843 回答
0

你可以做类似的事情

char Org="http://www.example.com/hello.html";
char New[200];
char Path="/hello.html";
memcpy(New,Org,strlen(Org)-strlen(Path));
New[strlen(Org)+strlen(Path)]=0;
printf("%s\n",New+12);
于 2013-05-02T16:40:40.797 回答