Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C socket client sending newline character

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));
like image 269
jpulman Avatar asked Mar 29 '14 02:03

jpulman


2 Answers

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';
like image 125
Vality Avatar answered Nov 15 '22 03:11

Vality


Also a good solution to your problem would be buffer[strcspn(buffer,'\n')] = 0.

You can see more details about strcspn in C here https://www.tutorialspoint.com/c_standard_library/c_function_strcspn.htm

Good Luck!

like image 28
student0495 Avatar answered Nov 15 '22 05:11

student0495