我正在閱讀這本書,Hands-On Network Programming with C,在我正在閱讀的當前章節中,我們正在構建一個 Web 客戶端。這個 Web 客戶端的功能之一是決議傳遞給它的 URL,以確定協議、主機名、檔案路徑等。部分決議功能如下:
void parse_url(char *url, char **hostname, char **port, char **path){
printf("URL: %s\n", url);
char *p;
p = strstr(url, "://");
char *protocol = 0;
if (p){
protocol = url;
printf("Protocol: %s\n", protocol);
*p = 0;
p = 3;
} else {
p = url;
}
printf("Protocol: %s\n", protocol);
if (protocol){
printf("Protocol: %s\n", protocol);
if (strcmp(protocol, "http")){
fprintf(stderr, "Unknown protocol, '%s'. Only 'http' is supported.\n",
protocol);
exit(1);
}
}
每當我傳入一個不使用 HTTP 的 URL 時,例如https://example.com(他們在書中使用的 URL),我都會得到以下輸出(我將額外的列印陳述句放在那里以進行除錯):
網址:https ://example.com
協議:https ://example.com
協議:https
協議:https
未知協議,“https”。僅支持“http”。
我的問題是,指向 URL 的協議如何被截斷為僅協議而不是以前的整個 URL?
uj5u.com熱心網友回復:
該陳述句p = strstr(url, "://");
將查找 in 的第一次"://"
出現url
并存盤 in 的第一個位元組的"://"
地址p
。因此,*p
將評估為':'
. 如果沒有"://"
找到,p
將等于NULL
。
如果"://"
找到了,protocol
會被設定為指向url的開頭,然后'\0'
被放置在p
所指向的地址。所以,如果之前url
包含"https://www.example.com\0"
,現在url
包含"https\0//www.example.com\0"
(包括'\0'
在末尾)。
C 中的字串以 . 結尾'\0'
。因此,任何處理字串的函式"https\0//www.example.com\0"
都會在第一次出現時停止處理字串'\0'
。因此,printf("%s", protocol)
將 print "https"
,strlen(p)
將回傳 5 等。
uj5u.com熱心網友回復:
作為替換':'
URL 中的'\0'
. 您可以獲取相同的資訊并使用指標數學來計算 URL 的協議部分中有多少字符,然后將其strncpy
僅用于將那么多字符放入另一個緩沖區。我們將該緩沖區初始化為零,以便在呼叫strncpy
.
這種方法不會破壞原始 URL 字串。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *get_protocol(char *url);
int main() {
char url[] = "https://www.example.com";
char *protocol = get_protocol(url);
printf("%s\n", protocol);
free(protocol);
return 0;
}
char *get_protocol(char *url) {
char *p = strstr(url, "://");
if (!p) return NULL;
size_t len = p - url;
char *result = calloc(len 1, 1);
if (!result) return NULL;
strncpy(result, url, len);
return result;
}
結果:https
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/498118.html
上一篇:為什么這個最小的HTTP測驗服務器有一半的時間會失敗?
下一篇:從領英請求資料