Reputation: 8941
SOCKET lhSocket; int iResult; lhSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); char *sendbuf = "this is a test"; iResult = send(lhSocket, sendbuf, (int)strlen(sendbuf), 0 );
printf("Bytes Sent: %ld\n", iResult);
I have client and Server program using sockets in C++ now i send a buffer it is received by server now when server acknowledge me back saying i got your packet i should get that in string format not bytes received : something. how to achieve that ?
My iresult returns me an integer value, I am sending a message over socket to server , i dont want to print it as Bytes sent : 14. I want to print the message sent as string to server. I am dealing with Sockets. How i can achieve this in C++
Upvotes: 0
Views: 2278
Reputation: 6926
if you use visual C++ 2008 or 2010 i think there is a function inbuilt to do your job.
something like itoa(int); will convert the given int and return a char *
pretty simple
its in stdlib.hlbtw
** make sure this is not the same in all compilers or distrubutions http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/ here is a link for reference
Upvotes: 0
Reputation: 273
Another opportunity is boost::lexical_cast<>
const int myIntValue = 12345;
const std::string myStringValue = boost::lexical_cast(myIntValue);
Upvotes: 1
Reputation: 106254
You're asking different things in the title and your post.
Converting int to string in C++ is done with
#include <sstream> std::ostringstream oss; oss << some_int; // do whatever with oss.str()...
as Tomasz illustrated.
To receive data from a socket, you need to make a further call to either recv() or read(). Your "send" call does not itself wait for the reply. recv() or read() accept character-array buffers to read the response into, but you will need to loop reading however much the calls return until you have enough of a response to process, as TCP is what's called a "byte stream" protocol, which means you are not guaranteed to get a complete packet, line, message or anything other than a byte per call.
Given the level of understanding your question implies, I strongly suggest you have a look at the GNU libC examples of sockets programming - there are some server and client examples - easily found via Google.
Upvotes: 0
Reputation: 11568
stringstream buf;
buf << 12345;
buf.str(); // string("12345")
buf.str().c_str(); // char* "12345"
Upvotes: 4
Reputation: 90072
sendbuf
is the string which you are sending. Print sendbuf
instead:
printf("Bytes Sent: %s\n", sendbuf);
Upvotes: 2