C socket client sending newline character
Asked Answered
L

2

5

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));
Ligulate answered 29/3, 2014 at 2:26 Comment(5)
memset the buffer with 0's before writing to it.Leatherjacket
@CantChooseUsernames Why would he do that out of interest?Jesselton
It will set every byte to 0 so OP doesn't have to do buffer[strlen(buffer) - 1] = '\0'; I guess the latter is better than using a memset. memset would be the way to go if OP was dealing with bitmaps or large buffers and structures.Leatherjacket
@CantChooseUsernames The buffer[strlen(buffer) - 1] = '\0'; is just to purge the new line that fgets end's its output buffer with and replace it with a null (to force the string to end). Though it is indeed a good idea sometimes to work with a zeroed buffer it is not strictly needed here. But yes, with a bitmap or something that is not ascii text you are correct.Jesselton
Note, that fgets expects the buffer size, so make it 256, or even better, fgets(buffer, sizeof buffer, stdin) if buffer is an array.Shoup
J
10

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';
Jesselton answered 29/3, 2014 at 2:38 Comment(3)
Would be wise to check fgets doesn't return NULL, and buffer[strlen(buffer)-1] == '\n' first. Otherwise you may access invalid memory (if there were a read error), or overwrite a valid character if the line were longer than 254.Shoup
Ah, you are completely correct, I was just being lazy and trying to keep it simple.Jesselton
@MattMcNabb there we go, it has been edited. Though I did not cover the part on fgets returning NULL as it is not really the question asked (Though is useful to remember)Jesselton
R
1

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!

Rosinski answered 14/1, 2017 at 21:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.