theCyberHawk
theCyberHawk

Reputation: 11

C++/TCP data transfer garbage

I'm a beginner C++/TCP programmer and I was doing a home assignment for file transfer using TCP in C++/VS2010/Windows 7.

I've created a client and a server that can listen to multiple clients on a network. When I send a request to the server requesting a file, I receive the correct size of file, but when I send data from server to client I get garbage.

I'm pretty sure I've done a stupid mistake somewhere with casting, but can't identify where. I am sending char* byte by byte and save them to a file on the client.

Any ideas what's wrong?

// client code: 
unsigned int packlen = 0;
unsigned int flength = 0;
char* data = NULL;
if((packlen = recv(sock, (char*) &flength, sizeof(unsigned int), 0)) == 
    sizeof(unsigned int))
{
    flength = (unsigned int) flength;
    data = new char[flength];
}
unsigned char current;
char* buffer;
unsigned int accumlength = 0;

for(unsigned int i = 0; i < flength; ++i)
{
    if((packlen = recv(sock, (char*) &current , sizeof(unsigned int), 0)) 
        != sizeof(unsigned int))
    {
        err_sys("Receiving packet transfer error., exit");
    }
    data[i] = current;
}
ofstream output(argv[2], ios::binary);
output.write(data, flength);
if(data)
{
    delete[] data;
    data = NULL;
}


// Server code:
char* data = NULL;
unsigned long length;
string fname; 

data = new char[stat_buf.st_size];
ifstream input(reqp->filename, ios::binary);
input.seekg(0, ios::end);
unsigned int length = input.tellg();
if(length != stat_buf.st_size)
{
    err_sys("Problems with file size");
}

send(cs, (char*) &length, sizeof(unsigned int), 0);
Sleep(1000);  // wait a bit

input.read(data, length); // read all file at once.
for(unsigned int i = 0; i < length; ++i)
{
    unsigned char current = data[i];
    send(cs, (char*) &current, sizeof(unsigned char), 0);
}

Thanks for your help.

Upvotes: 1

Views: 543

Answers (1)

mauve
mauve

Reputation: 2016

It looks like you are discarding quite a few bytes during the read loop:

recv(sock, (char*) &current, sizeof(unsigned int), 0)

Where current is an unsigned char but you ask it to read sizeof(unsigned int) bytes which are more than that. So recv() will write its result somewhere else (because it will write 4 bytes in current)

You should probably write:

recv(sock, (char*) &current, 1, 0)

Even though that is terribly inefficient it should at least work.

Upvotes: 1

Related Questions