in a function, that gets unsigned char && unsigned char length,
void pcap_callback(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet)
{
std::vector<unsigned char> vec(packet, packet+pkthdr->len); // optimized from foo.
std::stringstream scp;
for (int i=0;i<pkthdr->len;i++) {
scp<<vec[i];
}
std::string mystr = std::string(scp.rdbuf()->str());
std::cout << "WAS: " << packet << std::endl;
std::cout << "GOOD: " << scp.str() << std::endl;
std::cout << "BAD: " << scp.str().c_str() << std::endl;
std::cout << "TEST: " << mystr.size() << std::endl;
assert(mystr.size() == pkthdr->len);
}
Results:
- WAS: prints nothing (guess there is a pointer to const.. case)
- GOOD: prints data
- BAD: prints nothing
- TEST, assert: prints that mystr.size() is equal to passed unsigned char size.
I tried:
- string.assign(scp.rdbuf());
- memcpy(char, scp.str(), 10);
- different methods of creating/allocating temporary chars, strings
No help.. it is wanted to get a std::cout'able std::string that contains data, (which was picked from foo, which was unsigned char, which was packet data).
Guessing either the original foo may not be null-terminated, or the problem is something like this - simple, but can't get in.. what are the things to look for here?
(this code is another attempt to use libpcap, just to print packets in C++ way, without using known C++ magic wrappers like libpcapp).
std::cout << "BAD: " << scp.str()->c_str() << std::endl;
even compiling?? The member functionstd::stringstream::str()
does not return a pointer. It returns an instance ofstd::string
. – Charles Salviafoo
contains a null byte, so when you print it as a C-string nothing is outputted. But your implementation of iostreams prints outstd::string
by iterating overstd::string::length()
bytes and printing each character, including characters which appear after the null. – Charles Salviapacket
buffer is supposed to contain binary data (which it probably is, judging from theu_char
type), you can't expect to be able to print it meaningfully to the console as text. You need to iterate over each byte and output it as decimal or hex. – Charles Salviastd::basic_string<t>::operator[]
? Plus it's a valid STL container so you can use anything that would normally iterate over an stl container (i.e.std::copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout, ""));
– Billy ONeal