1 关键解析函数
1.1 strstr()
函数原型:
extern char *strstr(char *str1, const char *str2);
str1: 被查找目标 str2: 要查找对象 返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。
例子:
char str[]="1234xyz";
char *str1=strstr(str,"34");
printf("%s",str1);
显示的是: 34xyz
1.2 strncmp()
strncmp函数为字符串比较函数,字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。
函数原型:
int strncmp(const char *str1, const char *str2, size_t n)
参数:
- str1 – 要进行比较的第一个字符串。
- str2 – 要进行比较的第二个字符串。
- n – 要比较的最大字符数。
返回值:
- 如果返回值 < 0,则表示 str1 小于 str2。
- 如果返回值 > 0,则表示 str2 小于 str1。
- 如果返回值 = 0,则表示 str1 等于 str2。
实例:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strncmp(str1, str2, 4);
if(ret < 0)
{
printf("str1 小于 str2");
}
else if(ret > 0)
{
printf("str2 小于 str1");
}
else
{
printf("str1 等于 str2");
}
return(0);
}
2 代码
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define METHOD_DECODE(mode) mode?"POST":"GET"
static char data[] =
"GET /joyent/http-parser.txt HTTP/1.1\r\n"
"Host: github.com\r\n"
"DNT: 1\r\n"
"Accept-Encoding: gzip, deflate, sdch\r\n"
"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n"
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/39.0.2171.65 Safari/537.36\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,"
"image/webp,*/*;q=0.8\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n"
"Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n\r\n";
struct http_parser_urt
{
char filename[32];
char method;
};
char parse_url(struct http_parser_urt * httpurl, char * strurl)
{
char ret = 0;
char * line_start = NULL;
char * line_end = NULL;
char * start_temp = NULL;
char * end_temp = NULL;
char * line_temp = NULL;
if( (httpurl == NULL)||(strurl == NULL) )
{
ret = 1;
return ret;
}
line_temp = (char *)strstr(strurl, "\r\n\r\n");
if (line_temp == NULL)
{
ret = 1;
return ret;
}
line_start = strurl;
line_end = (char *)strstr(line_start, "\r\n");
if (line_end == NULL)
{
ret = 1;
return ret;
}
if (strncmp(line_start, "GET ", 4) == 0)
{
httpurl->method = 0;
start_temp = line_start + 4;
}
else if (strncmp(strurl, "POST ", 5) == 0)
{
httpurl->method = 1;
start_temp = line_start + 5;
}
else
{
}
start_temp++;
end_temp = (char *)strstr(line_start, " HTTP");
strncpy_s(httpurl->filename, start_temp, end_temp-start_temp);
return ret;
}
int main(int argc, char * argv[])
{
char ret1 = 0;
struct http_parser_urt url_test1;
ret1 = parse_url(&url_test1, data);
if (ret1 != 0)
{
printf("解析失败...\r\n");
return 0;
}
printf("解析成功..\r\n");
printf("方法名为:%s\r\n", METHOD_DECODE(url_test1.method));
printf("文件名为:%s\r\n", url_test1.filename);
system("pause");
}
运行结果:
解析成功… 方法名为:GET 文件名为:joyent/http-parser.txt 请按任意键继续. . .
|