[英]String search in packet and printing packet data
如何在C中的數據包(包括標頭和有效負載)中進行字符串搜索? 我嘗試使用strstr(),但是由於我的目標MAC地址以0x00開頭,因此strstr()函數似乎在數據包中沒有任何作用。 此外,數據包中可能會有更多的0x00字節。 我需要逐字節搜索,還是有更快的方法?
另外,我可以使用%s
打印數據包數據嗎? 我嘗試了以下操作,但是沒有輸出。
while ((rc = pcap_next_ex(pcap, &pkthdr, &data)) >= 0)
printf("%s\n", data);
印刷:
您不能使用printf(“%s”,data)打印數據包。 這是因為當出現NULL字節('\\ 0')時終止打印,這在引用發送的數據時非常常見。 您可以使用以下命令從%str中打印%len個字節,而忽略NULL字節,但是由於大多數字節都是不可見的,所以它不會給您帶來任何幫助:
// len = pkthdr.len
printf("%.*s", len, str);
對於搜索,可以使用非標准函數strnstr:
#include <stdio.h>
#include <string.h>
char *strnstr(const char *haystack, const char *needle, size_t len)
{
int i;
size_t needle_len;
/* segfault here if needle is not NULL terminated */
if (0 == (needle_len = strlen(needle)))
return (char *)haystack;
for (i=0; i<=(int)(len-needle_len); i++)
{
if ((haystack[0] == needle[0]) &&
(0 == strncmp(haystack, needle, needle_len)))
return (char *)haystack;
haystack++;
}
return NULL;
}
int main()
{
char big_str[] = "abc\0cde\0efg\0";
printf("%s", strnstr(big_str, "efg", 12));
return 0;
}
但請閱讀以下內容: https : //stackoverflow.com/a/25705264/6814540
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.