TheAuzzieJesus
TheAuzzieJesus

Reputation: 607

Sending a string over a network using sockets in C++

I'm encountering issues sending a string over a TCP network where the string is sending additional characters that were not input.

For example, when I input the following string...

I get the following result on the receiving end.

Below is the code that I'm using to send the string.

string input;
printf("Please input what you want to send...\n");
printf(">");
cin >> input;

const char* ch = (const char*)&input;
int lengthOfBytes = sizeof(input);

for (int i = 0; i < lengthOfBytes; i++)
{
   n = send(socket_d, &*ch, 10, 0);
}

//Reading in characters.
if (ch == (const char*)'\r')
{
   cout << "\n";
}

And here is the code used for recieving the string.

int n;
int count = 0;
char byte;
n = recv(socket_d, &byte, 1, 0);
if (n <= 0)
{
    if (WSAGetLastError() != WSAEWOULDBLOCK) 
    {
        cout << "Terminated " << WSAGetLastError() << "\n";
        return;
    }
}
else
{
    cout << (char) byte;
    if ((char) byte == '\r')
        cout << "\n";
}

What am I doing wrong when sending the string across the network?

Upvotes: 2

Views: 9026

Answers (3)

Galik
Galik

Reputation: 48665

You have completely misunderstood how to access the string data from a std::string object. You need to use the methods std::string::data() and std::string::size() to get the string data itself like this:

Sender:

std::string input;

std::cout << "Please input what you want to send...\n";
std::cout << "> ";

cin >> input;

n = send(socket_d, input.data(), input.size(), 0);

// check for errors here..

I don't have windows so my client code may not be identical to what you need but it may be something a bit like this:

Receiver:

std::string s;

int n;
char buf[256];

while((n = recv(socket_d, buf, sizeof(buf), 0)) > 0)
    s.append(buf, buf + n);

if(n < 0)
{
    std::err << std::strerror(errno) << '\n';
    return 1; // error
}

// use s here

std::cout << "received: " << s << '\n';

Upvotes: 6

Steephen
Steephen

Reputation: 15854

const char* ch = (const char*)&input;
int lengthOfBytes = sizeof(input);

You have to correct above snippet as follows:

int lengthOfBytes = input.length()+1;
char * ch = new char [lengthOfBytes ];
std::strcpy (ch, input.c_str());

Upvotes: 0

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

You are doing just about everything wrong when sending the string. ch is not a pointer to the string's characters. lengthOfBytes is not the length of the string's characters. Go and research the basics of using the string class.

Upvotes: 4

Related Questions