Skip to content
Advertisement

socket recv function not returning updated value

Trying to create socket application using c (Linux) to constantly fetch data from a server For this I have created a loop and inside it the routine connects , send a command, receive some data and close the socket. It works fine for the first interaction but looks like the recv function failing to update the buffer variable from second iteration and others.

Tried to use the memset function to clear but that clears the variable and it comes always blank after first iteration

Any ideas ?

Here is the example of code I´m using

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> 
#include <string.h>

int main(int argc , char *argv[])
{
    char *message , server_reply[2000];
    struct sockaddr_in server;  
    int socket_desc;
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);

    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("192.168.1.10");
    server.sin_family = AF_INET;
    server.sin_port = htons( 23 );

    int count = 0;
    for (;;)
    {
        printf("nContador >> %in", count);
        count++;  
        connect(socket_desc , (struct sockaddr *)&server , sizeof(server));
        send(socket_desc , "commandr" , 2 , 0); 
        sleep(5);

//Receive a reply from the server
        recv(socket_desc, server_reply , 100 , 0);
        printf(server_reply); /// This always shows the same values as the first iteraction 
        sleep(10);
        close(socket_desc);
    }
    return 0;
}

Advertisement

Answer

You closed the socket at the end of the first iteration. After that, socket_desc is no longer a valid filedescriptor.

If you really want a new connection every time, the easiest fix is to put the line

socket_desc = socket(AF_INET , SOCK_STREAM , 0);

inside your loop.

As others have said: please check the return values, be prepared to handle cases where not all the reply was received in one go, and fix up the call to printf! Just because this code worked once, does not make it correct.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement