I am working on a tcp server and when writing to the client(telnet) after displaying the correct output in one line the next line will consist of random characters and letters.
here is the function where i am reading and writing from the server:
void manageConnection(int in, int out)
{
int readCount,bufCount;
char inBuf[BUF_LEN], outBuf[BUF_LEN], inData[BUF_LEN], hostname[40];
char prefix[100];
char endOfData = '\n';
int i, revCount;
char revBuf[BUF_LEN];
gethostname(hostname,40);
sprintf(prefix,"\tC%d", getpid() );
fprintf(stderr,"\n%s starting up\n",prefix);
sprintf(outBuf,"\n\n connected to TCP server on host: %s \n"\
"enter X to exit otherwise enter the"\
"string to do something cool\n",hostname);
write(out,outBuf,strlen(outBuf));
while(1)
{
bufCount = 0;
while(1)
{
readCount = read(in,inData,BUF_LEN);
if (readCount > 0 )
{
if ( (bufCount + readCount) > BUF_LEN)
{
fprintf(stderr,"buffer limit exceeded\n");
close(in);
exit(EXIT_FAILURE);
}
fprintf(stderr,"string from client is %s \n",inData);
memcpy(&inBuf[bufCount], inData, readCount);
bufCount=bufCount+readCount;
if (inData[readCount - 1] == endOfData)
{
break;
}
}
else if (readCount == 0 )
{
fprintf(stderr,"\n%s Client has closed connection\n",prefix);
close(in);
exit(EXIT_FAILURE);
}
else
{
sprintf(prefix,"\tC %d: while reading from connection", getpid() );
perror(prefix);
close(in);
exit(EXIT_FAILURE);
}
}
inBuf[bufCount-2] = '\0';
if (inBuf[0] == 'X')
{
break;
}
revCount = serverProcessing(inBuf,revBuf);
sprintf(outBuf," the server recieved %ld characters, which when the string is processed"\
"are:\n%s\n\n enter next string:",strlen(revBuf),revBuf);
write(out,outBuf,strlen(outBuf));
}
fprintf(stderr,"\n%s client has closed the connection\n",prefix);
close(in);
}
my current output:
terminal where i run the telnet command:
" enter X to terminate, otherwise enter string"
(input) apple
" the server recieved 7 characters which when processed is ApPlE"
"@#V#!@"
on the server terminal:
" client entered apple"
"@V"
EDIT: i added the line > inBuf[bufCount-2] = '\0'; as mentioned in the comments for null terminating my string
on the client side i recieve no more rubbish letters but the letters still appear on the server side