Search code examples
csocketsstrcmp

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


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);
}

Solution

  • 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)
            {
            }