0
votes

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++

6
Assuming you want to convert iResult to string, you can explore itoa or it's variants.Chubsdad
OP: The title of your question and your question completely contradict each other. Please clarify...Thanatos
Also you can explore sprintf for this purposeChubsdad

6 Answers

2
votes

sendbuf is the string which you are sending. Print sendbuf instead:

printf("Bytes Sent: %s\n", sendbuf);
4
votes
stringstream buf;
buf << 12345;
buf.str(); // string("12345")
buf.str().c_str(); // char* "12345"
1
votes

Another opportunity is boost::lexical_cast<>

const int myIntValue = 12345;
const std::string myStringValue = boost::lexical_cast(myIntValue);

0
votes

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.

0
votes

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

0
votes

Take a look at itoa which converts an integer to a string.