Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector<char> and sockets

Is there a way to call send / recv passing in a vector ?

What would be a good practice to buffer socket data in c++ ? For ex: read until \r\n or until an upper_bound ( 4096 bytes )

like image 974
Chris Batka Avatar asked Sep 09 '09 14:09

Chris Batka


3 Answers

std::vector<char> b(100); 
send(z,&b[0],b.size(),0);

Edit: I second Ben Hymers' and me22's comments. Also, see this answer for a generic implementation that doesn't try to access the first element in an empty vectors.

like image 103
sbi Avatar answered Oct 05 '22 11:10

sbi


To expand on what sbi said, std::vector is guaranteed to have the same memory layout as a C-style array. So you can use &myVector[0], the address of the 0th element, as the address of the start of an array, and you can use myVector.size() elements of this array safely. Remember that those are both invalidated as soon as you next modify the vector though!

like image 21
Ben Hymers Avatar answered Oct 05 '22 12:10

Ben Hymers


One thing to watch out for: &v[0] is technically not allowed if the vector is empty, and some implementations will assert at you, so if you get buffers from others, be sure they're not empty before using this trick.

C++0x's vector has a .data() member function (like std::string's) to avoid this problem and make things clearer.

like image 26
me22 Avatar answered Oct 05 '22 13:10

me22