How can I do a string search in a packet (including headers and payload) in C? I tried using strstr(), but because my dest MAC address begins with a 0x00, the strstr() function seemed to not go any further into the packet. Furthermore, there is likely to be more 0x00 bytes within the packet. Do I need to do a byte-by-byte search, or is there a faster way?
Also, can I print the packet data using %s
? I tried the following, but there was no output.
while ((rc = pcap_next_ex(pcap, &pkthdr, &data)) >= 0)
printf("%s\n", data);
Printing:
You can not print the packet using printf("%s", data) . This is because printing is terminated when a NULL byte ('\\0') is occured, which is very frequent when referring to transmitted data. You could use the following to print %len bytes out of %str while ignoring NULL bytes, but it won't get you any far since most bytes are invisible:
// len = pkthdr.len
printf("%.*s", len, str);
As for searching, you can use the non-standard function 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;
}
but read this : https://stackoverflow.com/a/25705264/6814540
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.