Search code examples
cnetwork-programmingstrcmpstrcpy

C strcmp not working


So I have the following code and basically buffer is supposed to hold a string, "NOT FOUND" which is given by the server I'm connecting to. It is done by the recvfrom() system call in the first function block.

The problem is it is still going to my if condition, if (strcmp(buffer, "NOT FOUND") != 0), and not the else block below. I'm not sure whats wrong.

I also checked that the server does return "NOT FOUND", but upon printing buffer, prints: "NOT FOUNDJ�".

BUFFER_SIZE is 80

void recvFromServer(int sd, char* buf) {

    struct sockaddr_in6 client;
    socklen_t client_len = sizeof(client);

    int rd = recvfrom(sd, buf, BUFFER_SIZE, 0, (struct sockaddr *)&client, &client_len);
    if (rd < 0) {
        printf("ERROR: recvfrom() failed\n");
        return;
    }

    char host[BUFFER_SIZE], service[BUFFER_SIZE];
    int r = getnameinfo((struct sockaddr *)&client, client_len, host, sizeof(host),
                    service, sizeof(service), 0 | NI_NUMERICHOST);

    if (r < 0) {
        printf("ERROR: getnameinfo() failed\n");
        return;
    }

}

recvFromServer(sd, buffer);

printf("L %s\n", buffer);
char address[80], port[80];

if (strcmp(buffer, "NOT FOUND") != 0) {
    char *index = strchr(buffer, ' ');
    strncpy(address, buffer, index - buffer);
    address[strlen(address)] = '\0';
    strcpy(port, &buffer[index - buffer + 1]);
    printf("%s\n", address);
    printf("%s\n", port);
    sendMessageUDP(argv[4], sd, address, port);
} else 
    printf("Not Found\n");

Solution

  • You have to add terminating null-character to what you received before treating it as string.

    Assuming that declaretion of buffer is char buffer[BUFFER_SIZE];,

    int rd = recvfrom(sd, buf, BUFFER_SIZE, 0, (struct sockaddr *)&client, &client_len);
    if (rd < 0) {
        printf("ERROR: recvfrom() failed\n");
        return;
    }
    buf[rd >= BUFFER_SIZE ? BUFFER_SIZE - 1 : rd] = '\0'; /* add this line here */