Question

I am working with Winpcap library and I am facing a performance problem. When I call to

pcap_next_ex(fp, &header, &pkt_data) 

I get a const char* array with the packet data at pkt_data.

Now I want to modify some part of it, so I figured out this way:

std::vector<char> send_pkt(pkt_data, pkt_data + header->caplen); 

(header->caplen being the packet length) And now I can play with it, and send it down.

But, I got network delays up to 2000 ms, so I profiled the code at VS 2013, and it seems like that line of code is eating too much cpu cycles. I suppose it is because the packet array is copied entirely to the vector.

So my question is, what can I do to modify the original const char *pkt_data array in a fast way?

Thank you very much!

EDIT: Finally solved the problem. The winpcap driver was causing all the trouble, because it had the mintocopy property set too high (16000 by default), so with low traffic, like running a ping, the buffer didn't get full, and generated the delay. Calling to pcap_setmintocopy(fp, 10) did the trick.

For the packet (const char *) modifying, I used the casting solution provided below with success, in spite of the risk of modifying something marked as a constant, It worked and now I accomplished the objective perfectly.

u_char * send_pkt = const_cast<u_char *>(pkt_data);
Was it helpful?

Solution

I'll go ahead and speak the unspeakable: you could cast away const from the pointer, and then modify the data. Of course by doing so you will be entering the realm of Undefined Behavior, and thereby introducing the possibility of crashes, incorrect results, Flying Nose Daemons, etc. But the compiler will allow you to do it, so if you're desperate and nothing else is sufficient, you could give it a try and see what happens. Keep in mind that even if it seems to work on your machine, that doesn't imply it will necessarily work on other platforms.

Before doing anything rash, though, I'd first try this: permanently allocate a large-enough char array, memcpy() the const string into said array, and modify the array however you need to. memcpy() is quite efficient, since (unlike your vector approach) it does not require any dynamic allocation or freeing of memory from the heap. See if that is fast enough for you.

OTHER TIPS

what can I do

Nothing. You shall not modify anything behind a const char*.

I suppose it is because the packet array is copied entirely to the vector.

Yes, probably. If you want to modify data, you need to own it, and in this scenario unless you copy it you do not own it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top