[英]More optimal way to find a specific word in a string buffers C
I've made an app that parses HTTP headers. 我制作了一个解析HTTP标头的应用。 I'm trying to find if there is a better way to filter HTTP packets by POST method than the one I've come up with.
我试图找到一种比我提出的方法更好的通过POST方法过滤HTTP数据包的方法。 What I am trying to accomplish is to take advantage of the fact that I know that all the POST methods packet strings start with "POST".
我要完成的工作是利用我知道所有POST方法数据包字符串均以“ POST”开头的事实。 Is there a way to search for the first word of a string, store it and then use a condition with it?
有没有一种方法可以搜索字符串的第一个单词,存储它,然后对其使用条件? My code works but I would prefer not to search for the whole packet for a "POST" - you never know when you get the word "POST" inside a GET packet, for example.
我的代码可以工作,但是我不希望在整个数据包中搜索“ POST”-例如,您永远不知道何时在GET数据包中看到单词“ POST”。
char re[size_data];
strncpy(re,data,size_data); //data is the buffer and size_data the buffer size
char * check;
check = strstr(re,"POST");
if(check!= NULL)
{ *something happens* }
Since you only want to check for the string "POST" at the beginning of the packet, you can use the strncmp
function, eg 由于只想在数据包的开头检查字符串“ POST”,因此可以使用
strncmp
函数,例如
if ( strncmp( re, "POST ", 5 ) == 0 )
{
// this is a POST packet
}
As noted by @jxh in the comments, the strncpy
may cause problems, since it won't null terminate the string unless the string length is less than size_data
. 正如@jxh在评论中指出的那样,
strncpy
可能会引起问题,因为除非字符串长度小于size_data
否则它不会使字符串终止。 To make sure the string is properly terminated, the code should look like this 为确保字符串正确终止,代码应如下所示
char re[size_data+1];
strncpy(re,data,size_data);
re[size_data] = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.