C socket client sending newline character

jpulman picture jpulman · Mar 29, 2014 · Viewed 7.1k times · Source

Hi i am pretty new to socket programming and I've written a simple client/server system to send data over a socket. I've gotten it working so that I can send a string to the server and receive a reply.

Now I am trying to get the server to recognize command being sent from the client, but everything I send from the client has a newline character on the end. I know I can handle this from the server side, but is there a way to remove the newline character from the client side?

Here is the code which does the writing:

printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));

Answer

Vality picture Vality · Mar 29, 2014

Yes indeed, your issue is not that the socket is adding new lines (sockets never process or change data) Instead your call to fgets is simply catching the newline you type. You can remove it with this handy one liner:

buffer[strlen(buffer) - 1] = '\0';

which must be between the fgets and the write.

To be a little safer it would be better to use

if('\n' == buffer[strlen(buffer) - 1])
    buffer[strlen(buffer) - 1] = '\0';