【发布时间】:2015-02-02 19:13:03
【问题描述】:
我正在尝试编写解析 HTTP GET 请求并检查“主机”是否为 www.bbc.co.uk 的代码。
这是我的工作代码:
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。没有 3rd 方库]
非常感谢!
【问题讨论】:
-
这取决于你想成为多么迂腐,而这个细节在帖子中完全没有。有多少字符串需要采用预期的格式?如果你不关心,就做
if strstr(data,"www.bbc.co.uk")) printf("BBC WEBSITE!\n");