Question

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));
Was it helpful?

Solution

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';

OTHER TIPS

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top