Skip to content
Advertisement

(Socket operation on non socket) error while trying to receive data on a TCP server

What I want to do is send a message (which I type on the terminal) from the client to the server. I’m getting this error on the server when I try to call the recv() function. As you can see, the client doesn’t show errors.

enter image description here

This is the code I’ve written for the server side:

#define BUFFERLEN 1024

int main(int argc, char **argv)
{
    char name[BUFFERLEN];

    int sockfd_serv, sockfd_cli, port;
    struct sockaddr_in server_addr, client_addr;

    sockfd_serv = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd_serv == -1)
    {
        perror("Error abriendo el socket");
        exit(1);
    }

    bzero((char *)&server_addr, sizeof(server_addr));

    port = atoi(argv[1]);

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(port);

    //Asignamos un puerto al socket
    if (bind(sockfd_serv, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("Error al asociar el puerto a la conexión");
        close(sockfd_serv);
        return 1;
    }

    //Ponemos el servidor a escuchar
    listen(sockfd_serv, 5);
    printf("Escuchando en el puerto %dnn", ntohs(server_addr.sin_port));

    while (1)
    {
        int long_cli = sizeof(client_addr);
        //Aceptamos la conexión de un cliente
        if (accept(sockfd_serv, (struct sockaddr *)&client_addr, &long_cli) == -1)
        {
            perror("Error al aceptar conexión");
            close(sockfd_serv);
            return 1;
        }

        printf("Conectado con %s:%dn", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port));

        int nombre = recv(sockfd_cli, &name, BUFFERLEN, 0);
        if (nombre == -1)
        {
            perror("Name error");
            return 1;
        }

        printf("%s", name);
    }
    return 0;
}

I’m confused because I’m already checking that the socket is created properly. What does “non-socket” refers to?

Advertisement

Answer

You never initialize sockfd_cli. Odds are, it’s zero, and that’s your standard input terminal and not a socket. You need to store the return value from accept in sockfd_cli.

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