数据包中的字符串搜索和打印数据包数据
String search in packet and printing packet data
如何在 C 中的数据包(包括 headers 和负载)中进行字符串搜索?我尝试使用 strstr(),但因为我的目标 MAC 地址以 0x00 开头,strstr() 函数似乎无法深入数据包。此外,数据包中可能有更多的 0x00 字节。我需要进行 byte-by-byte 搜索,还是有更快的方法?
另外,我可以使用%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[=11=]cde[=11=]efg[=11=]";
printf("%s", strnstr(big_str, "efg", 12));
return 0;
}
但是读这个:
如何在 C 中的数据包(包括 headers 和负载)中进行字符串搜索?我尝试使用 strstr(),但因为我的目标 MAC 地址以 0x00 开头,strstr() 函数似乎无法深入数据包。此外,数据包中可能有更多的 0x00 字节。我需要进行 byte-by-byte 搜索,还是有更快的方法?
另外,我可以使用%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[=11=]cde[=11=]efg[=11=]";
printf("%s", strnstr(big_str, "efg", 12));
return 0;
}
但是读这个: