我正在嘗試編寫解析HTTP GET請求並檢查「主機」是否爲www.bbc.co.uk的代碼。C獲取字符串中的字符串的一部分
這是我的工作代碼:
char data[] = "GET /news/ HTTP/1.1\nHost: www.bbc.co.uk\nConnection: keep-alive";
unsigned int size = strlen(data);
if (size>3 && data[0] == 'G' && data[1] == 'E' && data[2] == 'T'){ //If GET Request
int host_index = -1;
for (int i=4; i<size-4; i++){
if (data[i] == 'H' && data[i+1] == 'o' && data[i+2] == 's' && data[i+3] == 't'
&& data[i+4] == ':' && data[i+5] == ' '){
host_index = i+6;
}
}
if (host_index != -1 && size > host_index+11 &&
data[host_index] == 'w' && data[host_index+1] == 'w' && data[host_index+2] == 'w' &&
data[host_index+3] == '.' && data[host_index+4] == 'b' && data[host_index+5] == 'b' &&
data[host_index+6] == 'c' && data[host_index+7] == '.' && data[host_index+8] == 'c' &&
data[host_index+9] == 'o' && data[host_index+10] == '.' && data[host_index+11] == 'u' &&
data[host_index+12] == 'k')
{
printf("BBC WEBSITE!\n");
}
}
我覺得這是不是很多很多的代碼。我怎樣才能使這個代碼更緊湊?
[請隨時給普通C.任何第三方庫]
非常感謝!
這取決於你想成爲如何迂腐,這個細節完全是在帖子中丟失。需要多少字符串以預期的格式?如果你不在乎,只要做'if strstr(data,「www.bbc.co.uk」))printf(「BBC WEBSITE!\ n」);' – chux 2014-12-04 21:02:32