0

I am trying to extract an image from a HTTP stream. I have a requirement of using C++ and no other library, except for libpcap to capture packets. Here is what I am doing:

if ((tcp->th_flags & TH_ACK) != 0) {
                i = tcp->th_ack;
                const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp);
                size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);
                std::string temp(payload);
                dict.insert(std::pair<u_int,std::string>(tcp->th_ack,temp));
        }

And then I concatenate all packets which have the same ACK number:

 std::string ss;
 for(itt=dict.begin(); itt!= dict.end(); ++itt) {
                std::string temp((*itt).second);
                ss.append(temp);
  }
  std::ofstream file;
  file.open("image.jpg", std::ios::out | std::ios::binary)
  file << ss;
  file.close();

Now when I write ss to a file, the size of the file is way less than the image that was transmitted. Is this the right way to write a binary file?

I am trying to do this in C++

Community
  • 1
  • 1
ACC
  • 2,488
  • 6
  • 35
  • 61

1 Answers1

1

Using std::string will cut your data at the first null-terminating character (even if std::string is not a null-terminated string). The constructor of std::string takes a char* and assumes a null terminated string. Here is a proof of that:

char sample [] = {'a', 'b', '\0', 'c', 'd', '\0', 'e'};
std::string ss(sample);

You should use a std::vector to store your data instead.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • I realized that I need to change the byte order before writing the data to a file. How do I do that for a block of data? for `long` and `short` I can use `ntohs` and `ntohl`. How do I do it for a vector of bytes? – ACC Oct 01 '12 at 03:52