[Network Programming] Is it possible to check the string sent by the client on the server?

Asked 2 years ago, Updated 2 years ago, 139 views

retval=recv(clnt_socks[job1],buf,BUFSIZE,0);
// // buf[retval]='\0';

if (strcmp(answer, buf) == 0) {
    for (i = 0; i < clnt_cnt; i++) {
        //...
    }
}
else {
    for (i = 0; i < clnt_cnt; i++) {
        //...
    }
}

The above code is the code that the client clnt_socks[job1] receives the message from the server and compares it with answer in an if statement.

[Question] By the way, even if buf and answer match, is the comparison method wrong to else statement?

answer is

{" [strawberry] \n"," [computer] \n"," [car] \n"," [airplane] \n"," [summer] \n"}

It's one of the fields.`

c network-programming socket client-server

2022-09-20 21:53

1 Answers

Moving to the else statement means that strcmp did not return zero.

Since I don't have any communication knowledge, I'll tell you two suspicious parts from the perspective of simple string comparison.

In the question, answer is followed by '\n' for each sentence, and I don't know how buf is obtained, but you have to make sure it's followed by '\n'. For example, if you receive an input with the fgets function, the string is followed by '\n', but if you receive a string with the get or scanf function, the string is not followed by '\n'. So don't just look at the visible letters, but print out the values of the invisible parts in ASCII and see if they're the same.

And if answer reads the value of the text file as fgets, and the text file is a Windows-generated file, and you're lazy to copy it and use it on Linux, Linux reads the rewrites of the Windows-generated text file as '\r\n' instead of '\n'. Even if it's annoying, if you create and use files in the same OS environment, these problems won't happen.

I wrote it down above, but don't just look at the letters you see, and print out the values of the parts you can't see and see if they're the same.


2022-09-20 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.