Why strcmp function is not comparing the received command from the user with LIST ( without strcmp the function is working )

旧街凉风 提交于 2021-01-29 19:42:41

问题


I am new to socket programming, I am writing an FTP server without the client I have to access the server using netcat localhost port

void do_job(int fd)
{
    i,client;
    char command[DEFAULT_BUFLEN];
    while((client =recv(fd, command, strlen(command), 0)) >0 )
    {
                
        if (strcmp(command,"LIST") ==0)
        {
        }

in the main function :

if ((pid=fork()) == 0) {
    close(listenfd);
    do_job(fd);
    printf("Child finished their job!\n");
    close(fd);
    exit(0);
}

回答1:


You need to add a null terminator to the string in order to use strcmp(). Also, if they type a line ending with newline, that character will be in command, so you need to include it in the string you compare with.

When calling recv() the third argument should be the max amount you can store in the buffer. strlen(command) returns the length of a string that's already in the buffer, but you haven't initialized it. You can use DEFAULT_BUFLEN, and subtract 1 to allow room for the null terminator that will be added.

void do_job(int fd)
{
    i,client;
    char command[DEFAULT_BUFLEN];
    while((client =recv(fd, command, DEFAULT_BUFLEN - 1, 0)) >0 )
    {
        command[client] = '\0'; // add null terminator
        if (strcmp(command,"LIST\n") ==0)
        {
        }



回答2:


The code has numerous issues. You're appying strlen to an uninitialized array. This is undefined behavior, which in actual practice could return anything from 0 to values in excess of the array size.

The recv function fills buffers from a byte stream; it doesn't return null-terminated strings, and doesn't extract lines from the stream. recv will happily read a fragment of the network input stream which starts in the middle of one command and ends in the middle of another one.

In the actual FTP protocol, a command will not be a null-terminated string anyway.

FTP commands are "Telnet strings" terminated by the "Telnet end of line code" [RFC 959, 4.1.3, P. 34]

Basically the whole approach is too simplistic to be workable; the program needs some sort of character stream abstraction over the network input, so that it can parse the protocol properly.



来源:https://stackoverflow.com/questions/65636301/why-strcmp-function-is-not-comparing-the-received-command-from-the-user-with-lis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!